gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:43:54 44 4
gpt4 key购买 nike

使用 Entity entity = hibernateTemplate.get(Entity.class, id); 当我点击 entity.getChild() 这是一个 OneToOne 关系时,每隔一个 OneToOne关系也被加载。我使用 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 的获取。这是 hibernate 错误吗?我在他们的文档中找不到任何关于此行为的信息。

我的映射正确吗?

最佳答案

它似乎按设计工作:) 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 在 getC() 上加载。

关于此的更多信息 herehere .

关于java - 获取惰性 OneToOne 实体会获取同一对象内的所有其他 OneToOne 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56947355/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com