Hibernate:Hibernate对Fetch模式Eager进行的多个选择查询 [英] Hibernate: Multiple select queries made by Hibernate for Fetch mode Eager

查看:201
本文介绍了Hibernate:Hibernate对Fetch模式Eager进行的多个选择查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始在应用程序中使用Hibernate.另外,我正在使用JPA存储库来使用自定义查询.我有多个实体,它们之间有关系.我在联接列和缓存"中都将提取模式用作"EAGER".我观察到Hibernate正在进行多个选择查询以获取每个实体,而不是在单个查询中执行.

I have just started using Hibernate in my application. Also I'm using JPA repository for using custom query. I have multiple entities which have relationships between them. I have used Fetch mode as 'EAGER' on the join column and also using Cache. I observed that Hibernate is making multiple select queries to fetch each entity and not doing it in a single query.

下面是一个实体:

@Entity
@Table(name = "entity_a")
public class EntityA implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    ...

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "entity_a")
    @JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<EntityB> entityB = new HashSet<>();

我正在使用JPA自定义查询来获取我的实体,如下所示:

I'm fetching my entity as below, using JPA custom queries:

EntityA entityA = entityARepository.findOneById(id);

Hibernate对上述语句发出选择查询.

Hibernate issues a select query for the above statement.

每当我执行entityA.getEntityB()时,它都会在EntityB上发出另一个选择语句.如何避免这种情况.如何使用Hibernate一次选择两个实体?

Whenever I do a entityA.getEntityB() it issues another select statement on EntityB. How to avoid this. How can I get both entities in a single select using Hibernate?

推荐答案

EntityB是否包含名为entity_a的字段?名称应与mappedBy属性中声明的名称完全相同.

Does EntityB contain a field named entity_a? The name should be exactly as declared in the mappedBy attribute.

通常,JPA提供程序必须遵循FetchType.EAGER模式.这似乎是一个配置错误的问题.即便如此,尽管要求JPA提供者渴望地加载渴望的关联,但是并不能保证它将在单个查询中完成.有一个特定于Hibernate的注释可以用作提示:@Fetch(FetchMode.JOIN).试试看,看看是否可行.

In general, JPA providers are required to honor the FetchType.EAGER mode. This seems to be a misconfiguration issue. Even so, while the JPA provider is required to load eager associations eagerly, there is no guarantee it will be done in a single query. There is a Hibernate-specific annotation that can be used as a hint: @Fetch(FetchMode.JOIN). Try it out and see if it works.

这篇关于Hibernate:Hibernate对Fetch模式Eager进行的多个选择查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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