Hibernate setMaxResult on parent limit child collection too

拟墨画扇 提交于 2019-12-11 02:03:08

问题


I have a parent entity with a @ManyToMany(fetch=FetchType.EAGER) child collection.

I need to load only first record i found of Parent entity, so i load it using this criteria:

session.createCriteria(Parent.class).setMaxResult(1).uniqueResult();

Work fine, but the limit is applied to child collection too, and this is very bad.

How can i get only first record of parent, but all record of its child?

Thanks


回答1:


Just mark the collection of children as fetch = FetchType.LAZY, don't fetch it in the query and initialize the collection after the query if necessary:

Parent p = (Parent) session.createCriteria(Parent.class).setMaxResult(1).uniqueResult();
// if necessary:
Hibernate.initialize(p.getChildren());

If you really want to keep the association as eager fetched (which is a bad idea, IMO), then only load the ID of the parent in the query, and then get the parent:

Long parentId = (Long) session.createCriteria(Parent.class)
                              .setProjection(Projections.id())
                              .setMaxResult(1)
                              .uniqueResult();
Parent p = session.get(Parent.class, parentId);


来源:https://stackoverflow.com/questions/8430965/hibernate-setmaxresult-on-parent-limit-child-collection-too

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!