'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!



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 karim farhouti