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

Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans的更多相关文章

  1. about hibernate lazy load and solution

    about hibernate lazy load is that used when loaded again.it can increase efficienty and sava memory. ...

  2. Hibernate -- lazy加载

    Hibernate -- lazy加载 hibernate类级别懒加载: lazy:true(默认) //类级别懒加载 //load方法 //class lazy属性 //默认值:true load获 ...

  3. FW: How to use Hibernate Lazy Fetch and Eager Fetch Type – Spring Boot + MySQL

    原帖 https://grokonez.com/hibernate/use-hibernate-lazy-fetch-eager-fetch-type-spring-boot-mysql In the ...

  4. Hibernate第一篇【介绍Hibernate,简述ORM,快速入门】

    前言 前面已经学过了Struts2框架了,紧接着就是学习Hibernate框架了-本博文主要讲解介绍Hibernate框架,ORM的概念和Hibernate入门 什么是Hibernate框架? Hib ...

  5. Hibernate入门(4)- Hibernate数据操作

    Hibernate加载数据 Session.get(Class clazz, Serializable id) clazz:需要加载对象的类,例如:User.class id:查询条件(实现了序列化接 ...

  6. 【Hibernate那点事儿】—— Hibernate应该了解的知识

    前言: 最近由于有点时间,就像深入的学习一下Hibernate.之前只是简单的使用,并没领会它的妙处.这里就趁着分享的机会,好好整理一下. 这篇主要讲到了下面几个部分: Hibernate框架 Hib ...

  7. 攻城狮在路上(壹) Hibernate(十五)--- Hibernate的高级配置

    一.配置数据库连接池: 1.使用默认的数据库连接池: Hibernate提供了默认了数据库连接池,它的实现类为DriverManegerConnectionProvider,如果在Hibernate的 ...

  8. 【Hibernate 7】浅谈Hibernate的缓存机制

    一.Hibernate缓存机制简介 对于Hibernate本身来说,它的缓存主要包括三部分:session缓存(一级缓存).二级缓存.查询缓存. 1.1,session缓存 随着session的关闭而 ...

  9. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-007UserTypes的用法(@org.hibernate.annotations.Type、@org.hibernate.annotations.TypeDefs、CompositeUserType、DynamicParameterizedType、、、)

    一.结构 二.Hibernate支持的UserTypes接口  UserType —You can transform values by interacting with the plain JD ...

  10. hibernate报错:org.hibernate.MappingException: No Dialect mapping for JDBC type: -1

    解决方法:自定义一个Hibernate Dialect. package com.yourcompany.util ; import java.sql.Types; import org.hibern ...

随机推荐

  1. 01-WIN2012R2+SQL2016故障转移群集的搭建

    一.前期准备  1.1.准备4台机器 机器名 IP 功能 jf-yukong 192.168.10.200 做域控服务器 Jf-storage 192.168.10.201 做ISCSI存储服务器 J ...

  2. Git原理入门简析

    为了获得更好的阅读体验,建议访问原地址:传送门 前言: 之前听过公司大佬分享过 Git 原理之后就想来自己总结一下,最近一忙起来就拖得久了,本来想塞更多的干货,但是不喜欢拖太久,所以先出一版足够入门的 ...

  3. 就当我在扯淡,宇宙的bug

    Geohot说到“我打算建立一个组织让人们从人工智能模拟中‘越狱’,释放真正的人性.” 不知从何时开始,世界上的知名科学家,黑客等都开始怀疑我们所处世界的真实性. 我们的世界上是真实存在的吗?是否存在 ...

  4. 前端面试题集锦(一)之HTML部分

    前端的发展日新月异,前端开发也早已从原来的切图套页面,变成了现在的非常复杂的技术体系,近期由于找工作,面试了很多家单位,也总结了一部分前端面试中经常会遇到的面试类型,并一一解答.主要分为HTML.CS ...

  5. C语言连接mysql,用GCC编译

    1. main.c文件内容如下 #include <stdlib.h>#include <stdio.h>#include <winsock.h>#include ...

  6. 关于阿里云Mysql分页查询不走索引的问题

    需要修改阿里云中的MYSQL 配置参数 : eq_range_index_dive_limit 阿里云上默认是 10 , 这个参数 表示 in 查询 条件超过 10 个 就不走索引,走全表扫描.如果我 ...

  7. (三)(1)线程间通信---wait和notify的使用

    这篇博客记录线程间通信相关api使用以及理解. 首先第一点,我之前的博客里的线程之间也是通信的,但是他们的通信是建立在访问的是同一个变量上的,相当于是变量.数据层面上的通信,而下面要讲的是线程层面上的 ...

  8. 智能家居系列之——WIFI小车

    2017年准备搬新家了,一直关注着树莓派的论坛,看有没有新玩意,想着今年过年在杭州过年,头一次在城里过年,感觉特别无聊,没有麻将可以打,没有鞭炮可以放,只能在家做做小玩意.从小就对四驱车有兴趣,一直想 ...

  9. python 15 带参装饰器

    目录 2. 带参数的装饰器 3. 多个装饰器装饰一个函数 2. 带参数的装饰器 #在装饰器的基础上再套一层 def auth(argv): def wrapper(func): def inner(* ...

  10. .netcore CAP2.6 快速入门

    CAP介绍: CAP是一个用来解决微服务或者分布式系统中分布式事务问题的一个开源项目解决方案.可以解决跨服务器的数据一致性问题.一个简单的列子,如:订单系统创建订单后需要通知邮件通知用户下单成功,解决 ...