Search code examples
javahibernateormhqlcriteria

Why would Hibernate's createQuery and createCriteria return a different number of objects?


I have two rows in my table

select count(*) from PREFERENCE;

COUNT(*)
----------
2

and when I do

session.createQuery("from Preference").list();

I get two objects.

However, when I do

session.createCriteria(Preference.class).list();

I get three objects - with the first row repeated.

Why on earth would that happen?


Solution

  • The EAGER fetch associations are applied for:

    • retrieval via get() or load()

    • retrieval that happens implicitly when an association is navigated

    • Criteria queries

    • HQL queries if subselect fetching is used

    I assume you have one EAGER @OneToMany collection in your Preference entity.

    1. The HQL overides the default fetch plan therefore ignoring the EAGET @OneToMany association which will be represented as an uninitialised LAZY proxy.

    2. The Criteria query will select the Profile and for each Profile you have two children in your @OneToMany collection so unless you use distinct result you will get two parent rows pointing to the same entity.

      If you want distinct results you have to change your Criteria query to:

      session
          .createCriteria(Preference.class)
          .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
          .list();