FetchMode连接对Spring JPA存储库中的ManyToMany关系没有影响 [英] FetchMode join makes no difference for ManyToMany relations in spring JPA repositories

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

问题描述

我试图这样做:



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

当它产生n + 1个查询时我通过Spring JPA存储库执行 personRepository.findAll(); ,就好像我没有任何 @Fetch 设置。 (一个查询首先获取所有人,然后每个人查询一个查询)。
$ b 使用 @Fetch(FetchMode.SUBSELECT ) 有效,不过!它只生成2个查询。 (其中一人适用于所有人,另一人适用于团体)。所以hibernate对一些提取参数作出反应,而不是 JOIN



我有也尝试删除 EAGER 取而代之,但没有运气。

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

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

  public interface PersonRepository扩展JpaRepository< Person,Long> {
}

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

解决方案

通过许多论坛和博客来阅读您的问题(我想你可能在发布之前就已经完成了)我也认为如果你使用Query接口
(例如:session),那么@Fetch(FetchMode.JOIN)将被忽略.createQuery()),但如果使用
Criteria接口,它将被正确使用。



这实际上是Hibernate中一个从未解决的错误。这是
不幸的,因为很多应用程序使用Query接口,
不能轻易迁移到Criteria接口。



如果您使用查询你必须手动添加JOIN FETCH
语句到HQL。

https://forum.hibernate.org/viewtopic.php?p=2456562 =nofollow noreferrer> Hibernate论坛
Spring论坛
类似的问题1


I'm trying to do this:

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

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).

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.

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

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

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

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

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) will be ignored if you use the Query interface (e.g.: session.createQuery()) but it will be properly used if you use the Criteria interface.

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.

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

References Hibernate Forum Spring Forum Similar Question 1

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

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