我知道这个问题被问过好几次,但我找不到关于这个主题的明确示例和答案(我也尝试了其他可能的解决方案)。
我正在使用 Spring JPA
和 Hibernate
并尝试对 OneToONe 关系进行延迟获取。我有 2 个简单的实体类,一个存储库类和使用 h2 数据库延迟加载一个实体。我尝试了构建时字节码检测来实现这一目标,这些是我的类(class)。
A 级
@Entity
public class A {
private String name;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(optional = false, fetch = FetchType.LAZY, mappedBy = "a")
@LazyToOne(LazyToOneOption.NO_PROXY)
private B b;
}
B 级
@Entity
public class B {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "A_ID")
private A a;
}
存储库
public interface ARepository extends JpaRepository<A, Long> {
A findByName(String name);
}
pom.xml 字节码增强器
<plugin>
<groupId>org.hibernate.orm.tooling</groupId>
<artifactId>hibernate-enhance-maven-plugin</artifactId>
<version>${hibernate.version}</version>
<executions>
<execution>
<configuration>
<failOnError>true</failOnError>
<enableLazyInitialization>true</enableLazyInitialization>
</configuration>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
</plugin>
最后是用于 h2 数据库的 initdata.sql
insert into a (name, id) values ('a', 1);
insert into b (a_id, id) values (1, 1);
当我在测试类中调用 findByName()
方法时,它仍然对 A
和 B
执行 2 个查询。我怎样才能延迟获取 B
类?提前致谢。
最佳答案
在this教程已回答您的问题
That’s because Hibernate needs to know if it shall initialize the manuscript attribute with null or a proxy class. It can only find that out, by querying the manuscript table to find a record that references this Book entity. The Hibernate team decided that if they have to query the manuscript table anyways, it’s best to fetch the associated entity eagerly.
关于java - Hibernate OneToONe 延迟获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52260107/