Reputation: 4991
I have a entity like this
public class Student
{
private School school; //many to one...
//setter and getters omitted
}
public class School
{
private Set<Student>students; //Students...
private Set<Owner>owners; //Owners one to many....
}
I have my code is quite easy..
final Criteria criteria = session.createCriteria(Student.class)
.add(filters)
.setFetchMode("school",FetchMode.JOIN);
final List<Student>students = criteria.list();
But I would like to retrieve the Owners as well. Later I could do:
for(final Student student:students)student.getSchool().getOwners.size();
But this would generate another distinct
SQL query.
But I want to do it in a single Query is this possible?
I have tried:
final Criteria criteria = session.createCriteria(Student.class)
.add(filters);
final Criteria ownerCriteria = criteria
.createCriteria("school","school")
.createAlias("owners","owners");
final List<Student>students = criteria.list();
But this do not works because when I navigate through it:
for(final Student student:students)student.getSchool().getOwners.size();
Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role
Exception is thrown! Even I can see the inner join
in Hibernate SQL console..
but seems the Owner
collection is not populate.
Is there a workaround for this?
Upvotes: 0
Views: 1028
Reputation: 4239
You could use
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Upvotes: 1