获取惰性 OneToOne 实体会获取同一对象内的所有其他 OneToOne 实体

Fetching a lazy OneToOne entity fetches every other OneToOne entities within the same object

使用 Entity entity = hibernateTemplate.get(Entity.class, id); 当我点击 entity.getChild() 这是一个一对一关系时,所有其他一对一关系也会被加载。我使用 hibernate 5.4.1-Final.

我使用字节码增强如下:

<configuration>
    <failOnError>true</failOnError>
    <enableLazyInitialization>true</enableLazyInitialization>
    <enableDirtyTracking>false</enableDirtyTracking> 
    <enableAssociationManagement>true</enableAssociationManagement>
</configuration>

A.java

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

    @Id
    @Column(name = "ID_A")
    private String id;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ID_A")
    @LazyToOne(LazyToOneOption.NO_PROXY)
    private B b;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ID_A")
    @LazyToOne(LazyToOneOption.NO_PROXY)
    private C c;

...
getters/setters
...

B.java

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

    @Id
    @Column(name = "ID_A")
    private String id;

}

C.java

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

    @Id
    @Column(name = "ID_A")
    private String id;

}

所以当我这样做时

A a = hibernateTemplate.get(A.class, "100"); 
// triggers an Hibernate query only on A entity. The B and C aren't fetched => OK

// Hibernate: select a0_.ID_A as ID_A_27_0_ from A a0_ where a0_.ID_A=?

a.getB(); // ERROR : triggers two queries : one on C and one on B
// Hibernate: select c0_.ID_A as ID_A _26_0_ from C c0_ where c0_.ID_A =?
// Hibernate: select b0_.ID_A as ID_A _13_0_ from B b0_ where b0_.ID_A =?

即使我在 HQLQuery 中获取 B,我仍然有一个查询 C :

Query<A> queryA = hibernateTemplate.createHQLQuery("from A a join fetch a.b where a.id=:id", A.class);
queryA.setParameter("id", "100");
A a = queryA.uniqueResult(); // triggers an inner join
// Hibernate: select a0_.as ID_A1_27_0_, b1_.ID_A as ID_A1_13_1_ from A a0_ inner join B b1_ on a0_.ID_A=b1_.ID_A where a0_.ID_A=? 
a.getB(); // KO -> triggers a query to select C !
// Hibernate: select c0_.ID_A as ID_A1_26_0_ from C c0_ where c0_.ID_A=?

我曾尝试进行双重映射(指定了 mappedBy 的 OneToOne),但没有成功。 B和C的PK和A一样

我预计 a.getB(); 不会触发 C 的提取。这是休眠错误吗?我在他们的文档中找不到有关此行为的任何信息。

我的映射正确吗?

它似乎按设计工作:) b 和 c 属于相同的默认值 "LazyGroup"。如果需要加载b或c中的任何一个,则整个组都会加载。

引自字节码增强器文档:

Lazy attributes can be designated to be loaded together and this is called a "lazy group". By default, all singular attributes are part of a single group, meaning that when one lazy singular attribute is accessed all lazy singular attributes are loaded. Lazy plural attributes, by default, are each a lazy group by themselves. This behavior is explicitly controllable through the @org.hibernate.annotations.LazyGroup annotation.

只需在 b 字段上添加 @LazyGroup("b"),在 c 上添加 @LazyGroup("c"),它应该会按预期工作:b 将仅在 getB() 上加载,anc c 在 [= 上加载13=].

关于此的更多信息 here and here