1

I am using Spring Data JPA in Spring Boot. Even though I used Lazy Fetch, Hibernate is generating the SQLs for all associations in entity. Also I have used @OneToOne bi-directional mapping. in both directions used LAZY fetch. When I access data from Parent->Child its not loading the Child. But Child->Parent its loading eagerly. I checked, its building the sqls for associations. Really confused with this.

Parent Entity: Employee:

@Entity
@Table(name = "employee")
public class Employee {
    @Id
    @Column(name = "employee_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer employeeId;
    @Column(name = "employee_name")
    private String employeeName;
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "company_id")
    private Company company;
    //setters and getters
}

Child Entity: Address

@Entity
@Table(name = "address")
public class Address{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "address_id")
    private Integer addressId;
    @Column(name = "address_name")
    private String addressName;
    @OneToOne(mappedBy = "address", fetch = FetchType.LAZY)
    @JsonIgnoreProperties(value = { "address"})
    private Employee employee;
    //getters and setters
}

I used repository.findOne(id) in both cases.

For Parent->Child: I got result and sqls as below: SQL:

Hibernate: select employee0_.employee_id as employee1_1_0_, employee0_.company_id as company_5_1_0_, employee0_.employee_desgn as employee2_1_0_, employee0_.employee_email as employee3_1_0_, employee0_.employee_name as employee4_1_0_ from employee employee0_ where employee0_.employee_id=?

Output:

[{"employeeId":4,"employeeName":"kalyan","address":null,"projects":null}]

From Child->Parent: I got result and sqls as below: SQL:

Hibernate: select address0_.address_id as address_1_0_0_, address0_.address_name as address_2_0_0_ from address address0_ where address0_.address_id=?
Hibernate: select employee0_.employee_id as employee1_1_0_, employee0_.address_id as address_5_1_0_, employee0_.employee_desgn as employee2_1_0_, employee0_.employee_email as employee3_1_0_, employee0_.employee_name as employee4_1_0_ from employee employee0_ where employee0_.address_id=?

Output:

{"addressId":2,"addressName":"mykukun","employee":{"employeeId":3,"employeeName":"Krishna3"}}

Please let me know, what I need to do for Lazy Fetch to work from Child to Parent ? Thanks

Krish
  • 1,248
  • 4
  • 23
  • 51
  • That will not work as onetoone by default will not be proxied, there are different solutions for this based on your situation. Please refer https://stackoverflow.com/questions/1444227/making-a-onetoone-relation-lazy – Sreenath Reddy Nov 17 '17 at 10:53
  • Maybe this post [The best way to map a @OneToOne](https://vladmihalcea.com/2016/07/26/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/) will be helpful... – Cepr0 Nov 17 '17 at 11:17

0 Answers0