Hibernate setMaxResult on parent limit child colle

2019-07-22 10:15发布

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条回答
Summer. ? 凉城
2楼-- · 2019-07-22 10:57

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);
查看更多
登录 后发表回答