【问题标题】:How to tell Hibernate criteria to skip relations in deep level?如何告诉 Hibernate 标准跳过深层关系?
【发布时间】:2015-11-18 08:58:09
【问题描述】:

我有休眠实体GeUser 这个实体与Pick 实体有ManyToMany 关系,这个实体与ALgo 实体有OneToOne 关系,并且这个实体与DbMatch 实体有ManyToMany 关系。我的目标是获得 GeUser 实体但没有 picks.algo.matches 。我想在我的网络应用程序上使用 GeUser 对象,但对我来说不需要关于算法匹配的数据,所以我想在从数据库加载之前跳过它。

GeUser 实体:

...
@Entity
public class GeUser {
   ....
   @ManyToMany
   private List<Pick> picks = new ArrayList<Pick>(0);
   ...

选择实体:

@Entity
public class Pick {
   ...
   @OneToOne
   private Algo algo;
   ...

算法实体:

...
@Entity
public class Algo{
    ...
    // I want to skip this when GeUser entity is loading from db. Should be e.g. matches == null
    @ManyToMany
    protected List<DbMatch> matches = new ArrayList<DbMatch>(); 
    ...

GeUser dao 方法:

public GeUser getUser(int user_id) {

    Criteria criteria = session.createCriteria(GeUser.class);
    criteria.add(Restrictions.eq("user_id",user_id));

    List<GeUser> users = criteria.list();

    if (users.size() > 0) {
        return users.get(0);
    } else {
        return null;
    }

}

【问题讨论】:

  • 跳过关系是什么意思?
  • 对不起,匹配项应该为空,GeUser.picks.get(0).algo.matches = null。
  • 请把问题说清楚。 My goal is get GeUser entity but without last relation data 是什么意思?
  • 编辑了我的帖子,现在更好了吗?
  • 好多了!请查看我的答案,如果它符合目的,请接受。 :)

标签: java hibernate hibernate-criteria


【解决方案1】:

这是一个简单的情况,可以通过延迟加载来解决。您可以在Algo 中指定FetchType.LAZY matches。 matches 只会在您在活动会话中访问时加载。

...
@Entity
public class Algo{
    ...
    // I want to skip this when GeUser entity is loading from db. Should be e.g. matches == null
    @ManyToMany(fetch = FetchType.LAZY )
    protected List<DbMatch> matches = new ArrayList<DbMatch>(); 
    ...

有关延迟加载的更多详细信息,请按照以下教程进行操作:

希望对您有所帮助,如果您需要进一步的帮助,请随时发表评论!

【讨论】:

  • 感谢您为我指明了正确的方向,在阅读了有关休眠延迟加载的信息后,我了解它是如何工作的,但现在我有一个关于如何使用 spring 控制器和 jackson 不将匹配项传递给 Web 应用程序的新问题答案在这里stackoverflow.com/questions/28746584/…
猜你喜欢
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 2014-07-23
  • 2012-06-22
  • 2010-09-25
  • 2015-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多