It looks like the Criteria API ignores the lazyness of the associations when restrictions are set for associated entities (as discussed
here and
here).
The scenario is a Parent entity with a many-to-one (or one-to-one) relationship with a Child entity:
Code:
class Parent {
private String parentName;
private Child child;
// ... getters and setters ...
}
class Child {
private String childName;
// ... getters and setters ...
}
If you want to make a Criteria query to retrieve some Parent objects placing restrictions on the Child object(s) you would do it this way:
Code:
List results = session.createCriteria(Parent.class)
.add( Restrictions.eq("parentName", "John") )
.createCriteria("child")
.add( Restrictions.eq("childName", "Paul") )
.list();
Hibernate eagerly retrieves the Child entities regardless of the laziness of the association in the mapping document.
The workarounds proposed in the threads above have some issues and they don't allow (I think) for Example based queries.
I haven't found any comment about this behavior in the Hibernate docs nor any opened issue regarding this in Hibernate Jira. I think an Issue should be opened for this since the docs are misleading and the behavior seems wrong.
@gonzao_diaz: gracias por el ofrecimiento, pero creo que me apaño con el inglés