How to solve LazyInitializationException when using JPA and Hibernate

I am working on a project for a client who wants to use lazy initialization. They always get a "lazy initialization exception" when matching classes with the default lazy loading mode.

@JoinTable(name = "join_profilo_funzionalita", joinColumns = {@JoinColumn(name = "profilo_id", referencedColumnName = "profilo_id")}, inverseJoinColumns = {@JoinColumn(name = "funzionalita_id", referencedColumnName = "funzionalita_id")}) //@ManyToMany(fetch=FetchType.EAGER) - no exceptions if uncommented @ManyToMany private Collection<Funzionalita> funzionalitaIdCollection; 

Is there a standard template using JPA classes to avoid this error?

Fragments are welcome, thank you very much for your time.

+47
java orm lazy-initialization hibernate jpa
Feb 23 '09 at 17:04
source share
9 answers

Hibernate 4.1.6 finally solves this problem: https://hibernate.atlassian.net/browse/HHH-7457

You need to set the hibernate-hibernate.enable_lazy_load_no_trans = true property

Here's how to do it in Spring:

 <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="packagesToScan" value="com.mycompany.somepackage"/> <property name="jpaVendorAdapter" ref="hibernateVendorAdapter"/> <property name="jpaDialect" ref="jpaDialect"/> <property name="jpaProperties"> <props> <prop key="hibernate.enable_lazy_load_no_trans">true</prop> </props> </property> </bean> 

Voila; Now you don’t have to worry about LazyInitializationException when navigating your domain model outside of a sleep mode session (persistence-context in "JPA-talk")

+61
Aug 11 '12 at 9:10
source share

There are many ways to pre-select properties, so they are present after the session is closed:

  • Call the appropriate recipient. After entering the field in the bean, it appears after the session is closed.
  • You can initialize the field in an EJBQL query, find the JOIN FETCH keyword.
  • Turn on AvailableSettings.ENABLE_LAZY_LOAD_NO_TRANS if you are using a version of Hibernate that supports it.

Using these solutions may cause some problems:

  • Recipient calls can be optimized by the JIT compiler (sometimes it takes some time).
  • The objects you are trying to use JOIN FETCH can be linked through several "many" links associated with List. In this case, the resulting query returns mixed results, and Hibernate refuses to retrieve data in one query.
  • There is already some interesting bug related to the available settings .ENABLE_LAZY_LOAD_NO_TRANS . And there will be more, because, as the sleeping guys say: Note: this can happen outside of a transaction and is unsafe. Use with caution. You are on your own.

The best way is to try JOIN FETCH . If this does not work, try using getter. If this happens at run time by the JIT compiler, assign the result to a public static volatile Object .

Or stop using Hibernate ...

+16
May 10 '09 at 11:45
source share

Please note that you should not use hibernate.enable_lazy_load_no_trans pre Hibernate 4.1.7 since it leaks connections. See https://hibernate.onjira.com/browse/HHH-7524

+14
Sep 06
source share

LazyInitializationException means that you are calling the collection after closing the hibernation session or after the object has been separated from the session.

You need to either reconnect the object to the hibernation session, change the place where you call the collection, or move the border where the session closes to a higher level.

+7
Mar 23 '09 at 2:53
source share

OpenSessionInView is one template to solve this problem. Some info here:

http://www.hibernate.org/43.html

You will be careful when implementing this template and understand the consequences. Each time you move the lazy association in the view, it runs another SQL query to load the data. If your use cases are such that the number and size of these SQL queries is small, this may make a difference. Make sure that you, at a minimum, configure logging options so that you can see which Hibernate queries are “magically” running in the background to load data.

Also consider the kind of application you are writing. If you are not dealing with deletion (without web services, without an AJAX-based web client), then OSIV can work just fine. However, if the remote serializer starts to go around the entire graph of the object, it will most likely cause a ridiculous amount of SQL queries and damage your database server and applications.

+5
Feb 23 '09 at 18:19
source share

When you use a collection and want to initialize it with lazy loading, use this collection until the session is closed. If the session is close after the session, if you want to use it, you will get a lazyinitializeException, because by default it tries to try.

+4
Nov 02 2018-11-12T00:
source share

The best way to solve LazyInitializationException is to use the JOIN FETCH directive in your entity queries.

Downloading EAGER is bad for performance. In addition, there are anti-patterns, such as:

Which you should never use, because they either require that the database connection is open for visualization of the user interface (Open Session in View), or the database connection is necessary for every lazy association that is extracted outside the original save context ( hibernate.enable_lazy_load_no_trans ),

Sometimes you don’t even need entities, and the DTO projection is even better. You should receive objects only when you need to modify them. For read-only transactions, DTO forecasts are better .

+4
Sep 27 '16 at 11:13
source share

Oracle Java tutorials point out that "Enterprise beans support transactions, mechanisms that control concurrent access to shared objects." Therefore, to handle problems with Lazy Fetch, I create a stateless Java session with no Bean restrictions, and then get all the helper classes that I need before returning from the method. This avoids the exclusion of lazy sampling. Oracle also mentions this as the core J2EE Session Facade Phase template. This pattern seems to be better than some of the other practices mentioned.

+1
Oct. 26 '14 at 21:33
source share

I am working on a project whose goal is to solve common JPA problems when matching objects with DTO using ModelMapper. This issue has already been resolved by the project. Project Link: JPA Model Mapper

"Its crucial to performance is to declare objects as lazy loading, so we don’t need to retrieve all related entities every time we need some data. But this technique leads to some problems. The most common is LazyInitializationException, which can be quite annoying sometimes. . Most of the time we just need a null object for an unloaded object instead of the object that throws an exception on access ... "

Source: JPA Model Mapper

Therefore, in the project we are dealing with a LazyInitializationException by setting null for all not loaded objects. The examples below show how this works.

Transferring an entity that sets null for all unloaded objects:

 TypedQuery<SystemEntity> query = em.createQuery("select s from SystemEntity s where s.id = 1", SystemEntity.class); SystemEntity system = query.getSingleResult(); return new JpaModelMapper(em).mapEntity(system, SystemEntity.class); 

Transferring an entity to the DTO parameter for all unloaded objects:

 TypedQuery<SystemEntity> query = em.createQuery("select s from SystemEntity s where s.id = 1", SystemEntity.class); SystemEntity system = query.getSingleResult(); return new JpaModelMapper(em).mapEntity(system, SystemDTO.class); 

See JPA Model Mapper for more information.

0
Apr 17 '18 at 19:07
source share



All Articles