@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 ?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With