在双向一对多JPA / Hibernate查询中创建交叉获取 [英] Cross fetch created on bi-directional One-to-many JPA / Hibernate query

查看:190
本文介绍了在双向一对多JPA / Hibernate查询中创建交叉获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是基本的映射:

 客户端{
@OneToMany(mappedBy =client,cascade = CascadeType .ALL,fetch = FetchType.EAGER)
private Set< Group> groups = new HashSet< Group>();


Group {
@ManyToOne(cascade = CascadeType.ALL)
private Client client = new Client();
}

我遇到的问题是,当我查询客户端时,为每个 关联组获取完整客户端。我的查询非常简单,我已经尝试了标准和HQL。以下是一个示例条件查询:

  Criteria crit = getSession()。createCriteria(getPersistentClass()); 

crit.add(Restrictions.like(name,name);
crit.add(Restrictions.eq(state,state);

返回crit.list();

我做错了什么?

解决方案

修改客户端的映射,如下所示,

 客户端{
@OneToMany(mappedBy =client,cascade = CascadeType.ALL,fetch = FetchType.LAZY)
private Set< Group> groups = new HashSet< Group>();
}

/ p>

您可以热切或懒惰地获取关联的实体,fetch参数可以设置为FetchType.LAZY或FetchType.EAGER。EAGER will尝试使用外部联接select来检索关联的对象,而LAZY只会在关联对象首次被访问时触发select。@OneToMany和@ManyToMany关联默认为LAZY和@OneToOne和@ManyToOne默认为EAGER。



阅读API文档这里了解更多详情。

Here's the basic mapping:

Client {
    @OneToMany(mappedBy="client",cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    private Set<Group> groups = new HashSet<Group>();
}

Group {
    @ManyToOne (cascade=CascadeType.ALL)
    private Client client = new Client();
}

The problem I'm having is that when I query against Client, I'm getting a full client for each associated group. My queries are pretty simple and I've tried both criteria and HQL. Here's a sample criteria query:

    Criteria crit = getSession().createCriteria(getPersistentClass());

    crit.add(Restrictions.like("name", name);
    crit.add(Restrictions.eq("state", state);

    return crit.list();

What the heck am I doing wrong?

解决方案

Modify your mapping of Client as below,

Client {
    @OneToMany(mappedBy="client",cascade=CascadeType.ALL, fetch=FetchType.LAZY)
    private Set<Group> groups = new HashSet<Group>();
}

From the API docs,

You have the ability to either eagerly or lazily fetch associated entities. The fetch parameter can be set to FetchType.LAZY or FetchType.EAGER. EAGER will try to use an outer join select to retrieve the associated object, while LAZY will only trigger a select when the associated object is accessed for the first time. @OneToMany and @ManyToMany associations are defaulted to LAZY and @OneToOne and @ManyToOne are defaulted to EAGER.

Read the API docs here for more details.

这篇关于在双向一对多JPA / Hibernate查询中创建交叉获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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