本文介绍了FetchMode join 对 spring JPA 存储库中的多对多关系没有影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试这样做:

//...
class Person {
    @ManyToMany(fetch = FetchType.EAGER)
    @Fetch(FetchMode.JOIN)
    private Set<Group> groups;
//...
}

当我通过 Spring JPA 存储库执行 personRepository.findAll(); 时,它会生成 n+1 个查询,就像我没有设置任何 @Fetch 一样.(先查询一次获取所有人员,然后每人查询一次获取组).

it generates n+1 queries when I do personRepository.findAll(); through a Spring JPA repository, just as if I didn't have any @Fetch set. (One query first to get all the persons, and then one query per person to fetch the groups).

使用 @Fetch(FetchMode.SUBSELECT) 有效,不过!它只生成 2 个查询.(一个用于所有人,然后一个用于团体).所以 hibernate 对 some 获取参数做出反应,而不是 JOIN.

Using @Fetch(FetchMode.SUBSELECT) works, though! It only generates 2 queries. (One for all persons, and then one for the groups). So hibernate reacts to some fetch parameters, just not the JOIN.

我也尝试删除 EAGER 获取,但没有成功.

I have also tried removing the EAGER fetching with no luck.

//...
class Person {
    @ManyToMany()
    @Fetch(FetchMode.JOIN)
    private Set<Group> groups;
//...
}

我正在使用 Spring JPA,这是我的存储库的代码:

I am using Spring JPA, and this is the code for my repository:

public interface PersonRepository extends JpaRepository<Person, Long> {
}

JOIN 是不是不能通过 Spring JPA 工作,还是我做错了什么?

Does JOIN just not work through Spring JPA, or am I doing something wrong?

推荐答案

通过许多论坛和博客来阅读您的问题(我猜您可能在将其发布到此处之前已经这样做了)我也认为

Going through many forums and blogs to read for your problem (I guess you might have done that before posting it here) I too think that

@Fetch(FetchMode.JOIN) 如果使用 Query 接口将被忽略(e.g.: session.createQuery()) 但如果你使用它会被正确使用标准界面.

这实际上是 Hibernate 中从未解决的错误.它是不幸的是,因为很多应用程序使用 Query 接口和无法轻松迁移到 Criteria 界面.

This is practically a bug in Hibernate which was never resolved. It is unfortunate because a lot of applications use the Query interface and cannot be migrated easily to the Criteria interface.

如果你使用Query接口,你总是要添加JOIN FETCH手动将语句导入 HQL.

If you use the Query interface you always have to add JOIN FETCH statements into the HQL manually.

参考资料Hibernate 论坛春季论坛类似问题 1

这篇关于FetchMode join 对 spring JPA 存储库中的多对多关系没有影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 20:53