java - Hibernate OneToONe 延迟获取

标签 java hibernate spring-data-jpa lazy-loading one-to-one

我知道这个问题被问过好几次,但我找不到关于这个主题的明确示例和答案(我也尝试了其他可能的解决方案)。

我正在使用 Spring JPAHibernate 并尝试对 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() 方法时,它仍然对 AB 执行 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/

相关文章:

java - 为什么NumberFormat中需要以下2个方法?

java - 我不能在 2 个 Activity 之间传递太大的对象数组列表?

java - 使用 Volley 发送数据

java - 在国际象棋java中移动棋子

java - Hibernate @Where 注释不适用于继承

java - Spring 关注关注者

database - 错误 Jparepository java.lang.IllegalArgumentException

Axis2 找不到 Hibernate 配置文件

java - 使用 Hibernate 工具时出现不支持的 Major.minor 版本 51.0 异常

java - Spring JpaRepositor返回选定的pojo字段