Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Lazy loading not working in one to one association?

@Entity
public class Person {
    @Id
    @GeneratedValue
    private int personId;

    @OneToOne(cascade=CascadeType.ALL, mappedBy="person", fetch=FetchType.LAZY)
    private PersonDetail personDetail;

    //getters and setters
}

@Entity
public class PersonDetail {
    @Id
    @GeneratedValue
    private int personDetailId;

    @OneToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
    private Person person;

        //getters and setters

    }

when i do

 Person person1=(Person)session.get(Person.class, 1);

i see two queries being fired. one for fetching person data and another for person detail data.

As per my understanding only 1 query should have been fired that is for fetching person data not for person detail data as i have mentioned lazy loading. Why personDetail data is getting fetched along with person data ?

like image 690
M Sach Avatar asked Feb 01 '14 14:02

M Sach


People also ask

How do I fix lazy initialization exception?

The right way to fix a LazyInitializationException is to fetch all required associations within your service layer. The best option for that is to load the entity with all required associations in one query.

What is the result of lazy loading strategy in?

Lazy loading helps you render an application faster. It also improves user experience by enhancing the bootstrap and startup process. This guide will give you hands-on experience with lazy loading implementation by covering the following topics: Eager loading and its limitations.

How do I enable lazy loading?

Lazy loading means delaying the loading of related data, until you specifically request for it. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook. Lazy loading is pretty much the default.


1 Answers

Hibernate cannot proxy your own object as it does for Sets / Lists in a @ToMany relation, so Lazy loading does not work.

I think this link could be useful to understand your problem: http://justonjava.blogspot.co.uk/2010/09/lazy-one-to-one-and-one-to-many.html

like image 139
gipinani Avatar answered Sep 22 '22 12:09

gipinani