I have been suffering from infamous hibernate exception
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
Now the community is cheering over
<property name="hibernate.enable_lazy_load_no_trans" value="true"/>
saying it solves the problem but USE IT WITH CAUTION.
What they mean by use it with caution? What this property actually does?
Please give me any insights. Thanks in advance.
The problem with this approach is that you can have the N+1 effect.
Imagine that you have the following entity:
public class Person{
@OneToMany // default to lazy
private List<Order> orderList;
}
If you have a report that returns 10K of persons, and if in this report you execute the code person.getOrderList()
the JPA/Hibernate will execute 10K of queries. This is the N+1 effect, you will have no control about all the queries that will be executed.
Imagine now that Order is like below:
public class Order{
@OneToMany // default to lazy
private List<EmailSent> emailSentList;
}
Imagine now that you have a iteration with the person.getOrderList()
and for every Order order
you will do a order.getEmailSentList()
. Can you see the problem now?
For LazyInitializationException you can have some solutions:
select p from Person p join fetch p.orderList
. With this query you will have your list loaded from the database and will not have the N+1 effect. The problem is that you will need to write a JPQL for each case.If you still have any problem, check these links: