也在父级限制子集合上休眠setMaxResult [英] Hibernate setMaxResult on parent limit child collection too

查看:97
本文介绍了也在父级限制子集合上休眠setMaxResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有@ManyToMany(fetch = FetchType.EAGER)子集的父实体。

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?

谢谢

推荐答案

只要将子集合标记为 fetch = FetchType.LAZY ,不要在查询后抓取它并在查询后初始化集合(如果需要):

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

如果你真的想保持这个关联的渴望(这是一个坏主意,IMO),然后只加载查询中父代的ID,然后获取父代:

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

这篇关于也在父级限制子集合上休眠setMaxResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆