简体   繁体   中英

How to do lazy loading for this One to One relationship with JPA and Hibernate?

I'm learning lazy loading with JPA and Hibernate in a Spring Boot project. It is a simple project with 2 tables: student and passport. It is a One to One relationship and I see that the lazy loading is not working.

This is the code

student entity:

import javax.persistence.*;

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @OneToOne(fetch = FetchType.LAZY)
    private Passport passport;

    public Student() {

    }
}

Passport entity:

import javax.persistence.*;

@Entity
public class Passport {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String number;

    public Passport() {

    }
}

I'm running this method using debugger from Intellij and It looks like an eager loading because it select students and passports when this entityManager.find(Student.class, 20001L) is called. How can I do this to be a lazy loadung? Thank you!

In LAZY loading hibernate will try to make either a proxy object containing the id of the LAZY loaded entity.In order to do it needs to get the Foreign key in the Student table,which is not available in your example because you didn't specify the @JoinColumn, and depending on the value it will decide to either make a proxy object wrapping the passeport object and ready to be queried,or assign null to it. Since there's no foreign key present in the Student table,hibernate will always treat that OneToOne EAGER,because it has no clue if a passeport associated with student exists or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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