简体   繁体   English

嵌套的FETCH JOIN如何使用JpaRepository和@Query注释在Hibernate上工作?

[英]How nested FETCH JOIN works on Hibernate using JpaRepository and @Query annotation?

I have the following problem (pseudo-java-code): 我有以下问题(伪java代码):

Let me a class A,B,C with the following relationships: 让我一个A,B,C类,有以下关系:

@Entity
@Table(name = "A")
public class A {

  @OneToMany(mappedBy = "a")
  private B b; 

}


@Entity
@Table(name = "B")
public class B {

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "a_id")
  private A a;

  @OneToOne(mappedBy = "b", fetch = FetchType.LAZY)
  private C c;

}


@Entity
@Table(name = "C")
public class C {

  @OneToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "b_id")
  private B b;

}

I'm using JpaRepository with @Query annotation and I implemented the following query: 我正在使用带有@Query注释的JpaRepository,我实现了以下查询:

@Query("SELECT DISTINCT(a) FROM A a "
        + "LEFT JOIN FETCH a.b as b"
        + "WHERE a.id = :id ")
A findById(@Param("id") Integer id);

I want retrieve the informations about class A and B, but not C. Somehow (I don't know why) the query try to retrive also the relation between B and C. And then, with hibernate, start the lazy invocation for retrieving C. 我想要检索有关类A和B的信息,但不是C.不知何故(我不知道为什么)查询尝试检索B和C之间的关系。然后,使用hibernate,启动lazy调用以检索C 。

Naturally, if I fetch also the relation between B and C (adding LEFT JOIN FETCH bc as c ) that's not happen. 当然,如果我也获取B和C之间的关系(将LEFT JOIN FETCH bc as c添加LEFT JOIN FETCH bc as c ),那就不会发生。

My question is, why? 我的问题是,为什么? Why I'm forced to fetch all nested relations and not only the ones which I need? 为什么我被迫获取所有嵌套关系而不仅仅是我需要的关系?

thank you. 谢谢。 Carmelo 卡梅罗

Nullable @OneToOne relation are always eager fetched as explained in this post Making a OneToOne-relation lazy Nullable @OneToOne关系总是渴望获取,如本文所述, 使一个OneToOne关系变得懒惰

Unconstrained (nullable) one-to-one association is the only one that can not be proxied without bytecode instrumentation. 无约束(可空)一对一关联是唯一一个没有字节码检测就无法代理的关联。 The reason for this is that owner entity MUST know whether association property should contain a proxy object or NULL and it can't determine that by looking at its base table's columns due to one-to-one normally being mapped via shared PK, so it has to be eagerly fetched anyway making proxy pointless. 这样做的原因是所有者实体必须知道关联属性是否应该包含代理对象或NULL并且由于通常通过共享PK进行一对一映射而无法通过查看其基表的列来确定它,因此它不管怎么说,必须要急切地让代理变得毫无意义。

Shot in the dark, but there are some issues with lazy-loading @OneToOne -relationships. 在黑暗中拍摄,但延迟加载@OneToOne -relationships存在一些问题。 At least in older versions of Hibernate . 至少在旧版本的Hibernate I think (but can't seem to find any documentation) that this was fixed in one of the newer versions, so if you are not using a new version of Hibernate, try upgrading. 我认为(但似乎找不到任何文档)这是在一个较新的版本中修复的,所以如果你没有使用新版本的Hibernate,请尝试升级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM