为什么Hibernate有时会忽略FetchMode.JOIN? [英] Why Hibernate sometimes ignores FetchMode.JOIN?

查看:88
本文介绍了为什么Hibernate有时会忽略FetchMode.JOIN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有@ManyToOne关系的实体,我想通过一个查询使用进行检索.有时,Hibernate不尊重它,而是发出N + 1个SELECT.有时, 的意思是因为我不知道是什么触发了它,所以我遇到了在同一类上进行不同查询的情况,这种情况是否可能发生.

I have an entity with a @ManyToOne relation, which I'd like to retrieve with a single query, thus using @Fetch(FetchMode.JOIN). Sometimes Hibernate doesn't respect that and issues N+1 SELECTs. With sometimes I mean that since I don't know what triggers it, I have cases which on the same class for different queries this could happen or not.

这是带有我使用的注释的简化实体:

This is a simplified entity with the annotations I use:

@Entity
public class Employee {

    @ManyToOne
    @Fetch(FetchMode.JOIN)
    private Department department;

}

使用

CriteriaQuery<Employee> criteriaQuery = criteriaBuilder.createQuery(Employee.class);

Root<Employee> root = criteriqQuery.from(Employee.class);

TypedQuery<Employee> typedQuery = entityManager.createQuery(criteriaQuery);

List<Employee> employees = typedQuery.getResultList();

我希望一个查询能够同时获取Employee及其Department,例如

I would expect a single query to fetch both Employee and its Department, something like

select ... from Employee join Department on ...

相反,我对所有N个Employee都有一个第一选择,然后对所有Department个都选择N SELECT个(不考虑缓存).

instead I get a first select for all N Employees and then N SELECTs for all Departments (consider no cache).

我发现了许多类似的问题,但是他们的回答提出了解决方法,但没有解释为什么会这样.请避免出现建议使用延迟加载的答案:这不是我要的.

I've found many similar questions, but their answers suggest workarounds and do not explain why this is happening. Please, avoid answers suggesting to use lazy loading: it's not what I'm asking.

推荐答案

规则很简单:查询会忽略获取模式.当您编写查询时,您在告诉什么是联接的,什么不是联接的.

The rule is quite simple: Queries ignore fetch modes. When you write a query, you are telling what is joined and what is not joined.

仅当实体使用EntityManager.find(class, id)之类的方法加载实体时,或在其他某些实体图中导航并加载其关联时,才会考虑获取模式.

Fetch mode is only taken into account when entity is loaded with methods like EntityManager.find(class, id) or when navigating through some other entity graph and loading its associations.

这篇关于为什么Hibernate有时会忽略FetchMode.JOIN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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