Java Hibernate使用Criteria获取一对多

时间:2015-02-17 20:57:48

标签: java hibernate one-to-many many-to-one distinct-values

我有这样的实体

public class Student
{
    private School school;//many to one...
    //setter and getters ommited
}

public class School
{
    private Set<Student>students;//Students...
    private Set<Owner>owners;//Owners one to many....
}

我的代码非常简单..

 final Criteria criteria = session.createCriteria(Student.class)
 .add(filters)
 .setFetchMode("school",FetchMode.JOIN);
 final List<Student>students = criteria.list();

但是我想找回所有者以后我可以做

for(final Student student:students)student.getSchool().getOwners.size();

但这会生成另一个distinct SQL查询。

但是我想在一个查询中这样做可能吗?

我试过了。

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();

但这不起作用,因为当我浏览它时

for(final Student student:students)student.getSchool().getOwners.size();

Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role

抛出异常!!!即使我可以在inner join中看到Hibernate SQL console..,但似乎Owner集合还没有填充....

任何解决方法或我要求很多

任何帮助都非常感谢委内瑞拉的最佳问候。

1 个答案:

答案 0 :(得分:1)

您可以使用

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);