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.

asked Aug 18 '14 at 12:01
 
1  
this might help you – ankur-singhal Aug 18 '14 at 12:48
    
Looks like the link has changed to harezmi.com.tr/… – Steve Chambers Jul 1 at 10:15

3 Answers

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 orderyou will do a order.getEmailSentList(). Can you see the problem now?

For LazyInitializationException you can have some solutions:

  • Use the OpenInSessionInView approach. You will need to create a WebFilter that will open and close the transaction. The problem with is the N+1 effect.
  • Use the hibernate.enable_lazy_load_no_trans configuration, that is a hibernate and you will not be able to port your project to other JPA provider if needed. You also can have the N+1 effect.
  • Use the EJB feature named PersistenceContext Extended. With this you will keep the context opened of several transactions. The problems are: N+1 effect can happen, use a lot of server memory (entities will stay managed)
  • Use the FETCH in the query. With this approach you could do a JPQL/HQL like: 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 this link: http://uaihebert.com/four-solutions-to-the-lazyinitializationexception

answered Aug 18 '14 at 16:32
uaiHebert
1,345215
 
    
OpenSessionInView will never have this "N+1 effect", that would'nt make any sense. Only ONE session will be opened and every entity-lookup within that will be handled normally - most likely via JOINs, depending on your fields. You have obviously not understood how the open-session-in-view method works. The one and only problem with it is : in bad situations (and with bad coding) your user may not get any information if your transaction actually got rolled back or even failed, dending on your transaction-configuration. – specializt Oct 14 '14 at 11:20 
    
N+1 is not about several sessions, but is about several trips do the database. – uaiHebert Oct 14 '14 at 14:36
    
in this case these are the same thing - during a view-created session all of your entity attributes may or may not be fetched with a single "trip" - depending on your ORM-implementation and/or fetch configuration. – specializt Oct 15 '14 at 12:12 
    
I am not sure if you understood what I told up there. With open session in view you will have the N+1 effect, you will keep the transaction opened and for each get of a non fetched entity a new trip to the database will be done. I said about n+1 and fetch in a jpql, what is your point? – uaiHebert Oct 15 '14 at 18:39
    
ohgod ... that engrish is hard to decrypt, anyway : yes, you now discovered the primary aspect of lazy initialization. I recommend going deeper into the topic; such as the difference to eager-fetch, cardinalities and especially the fact that your "problem" is omnipresent and a JOIN FETCH will simply remove the DBMS-driver overhead for a few additional "trips" but also decrease the performance in large data-sets. JOINs may work for small data-sets exclusively. Hybrid approaches may also yield acceptable results. – specializt Oct 15 '14 at 19:39

Did you find this question interesting? Try our newsletter

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

This goes against how we can take advantage of Hibernate's enforcement of repeatable read semantics with the Session concept. When an object is first loaded and if the object is referenced again within the life of the session, then the same object is returned IRRESPECTIVE of whether this object has changed in the DB. This is the repeatable read semantics provided automatically by hibernate.

With this setting, you have no session providing this guarantee, so if you now access this data you will be getting the latest version of the data.

This might be fine. But consider the scenario where this object is held in some place for a long time and the data has changed considerably, so that the lazily fetched data is much different that the data already loaded when the session was alive. This is what you need to be concerned about.

To put it simple you can safely use this setting if your program is not affected by: How stale the data that was already fetched when in session to the data that will be fetched lazily out of session

But if this (your program is exposed to timing issues, when it might work fine one time and fail another time) is a concern, then fetch all the necessary data while in session.

answered May 25 at 19:25
ddalton
86827
 

Probably because there are better solutions, like @Transactional, where opening and closing sessions follows a very common pattern of "open a session then wrap everything in a try-catch-finally; catch rolls back and finally closes the session." This annotation is typically at the request-level for web apps and services.

Or if you need more granular control you can open sessions manually using a SessionFactory.

And as others have mentioned, lazy-loading is something you need to be aware of. It's not a silver bullet but it can be very helpful. Generally, if your apps are designed to have many small requests then its ok.

Eager loading can also be very bad. For example, when your object model has lots of many-to-many relationships but your requests don't use data more than one level deep.

Or you can just forget the whole thing for now. Use lazy loading until it becomes an issue. And if it does, you would have been better of with Mybatis anyway.

answered May 21 at 2:00
James Watkins
1,0491515
 
 
http://stackoverflow.com/questions/25362831/solve-hibernate-lazy-init-issue-with-hibernate-enable-lazy-load-no-trans

最新文章

  1. asp.netDataTable导出excel方法(1)
  2. 在Go语言中使用JSON(去掉空字段)
  3. winScp如何通过隧道代理进行远程连接
  4. maven编译项目时提示:cached in the local repository
  5. TypeScript 素描 - 模块
  6. C#中的AssemblyInfo 程序集信息
  7. Emgu学习笔记(一)安装及运行Sample
  8. dfs和bfs的简单总结
  9. redis编译 报告错误 jemalloc/jemalloc.h:没有那个文件或目录 解决.
  10. mockplus 原型设计工具
  11. [Swift]LeetCode161. 一次编辑距离 $ One Edit Distance
  12. 学习一下sticky-footer
  13. linux的基本操作2
  14. CentOS上部署.net core
  15. MySQL中的编码问题
  16. 团队作业第六次——团队Github实战训练
  17. acm模板生成
  18. grpc python quickstart
  19. python学习——大文件分割与合并
  20. ubuntu 玩转 nodejs

热门文章

  1. spring cloud 断路器 Hystrix
  2. 解决Sklearn中使用数据集MNIST无法获取的问题(WinError 10060)
  3. NFS Debian 服务器,CentOS 客户端
  4. 十款强大的IDEA插件-Java开发者的利器
  5. linux_密钥
  6. 实战SpringCloud响应式微服务系列教程(第三章)
  7. 关于多线程中sleep、join、yield的区别
  8. Codeforces 976D
  9. C#开发BIMFACE系列3 服务端API之获取应用访问凭证AccessToken
  10. 五大典型场景中的API自动化测试实践