Don’t be Lazy…InitializationException

Jean-Michel Bernard
2 min readMay 25, 2021

Seems to me that this was my nemesis during my decade or so of programming in Java.

So many times I’ve struggled on this, because I did not understand the bare bones of this exception.

The basis is actually simple: one property (at least) of a class is annotated with OneToMany or ManyToMany, and as by default these relationships are using lazy fetching, then when you try to access said property on your legitimately instanciated object fetched from your back-end layer, this exception is thrown and then ensues head scratching, googling, trial and error with eventually a solution… but also maybe not the best one.

I won’t go into technical details here, but below are a few anti-patterns that you should avoid:

  • Use explicit eager fetching
  • Set enable_lazy_load_no_trans to false
  • Set ‘Open Session In View’ to true

And what you should do instead:

  • You need to explicitly write the query that will bring the entity you want to manipulate, and use ‘join fetch’ on the table/entity that manages the property triggering the LazyInitializationException. If you use a repository class extending CrudRepository (or equivalent), then you need to annotate your method with Query and fill in the query accordingly.

Not clear? Let’s see some code examples.

Example 1: Explicit inline query.

// Explicit inline query
Query query = session.createQuery(""
+ "select e "
+ "from Entity e "
+ "join fetch e.property"
);

Example 2: Using a Repository to fetch data from the back-end.

// Imports...public interface MyRepository extends CrudRepository {    @Query(value = ""
+ "select e "
+ "from Entity e "
+ "join fetch e.property"
)
Entity findById(@Param("propertyId") Integer propertyId);
}

The ‘join fetch’ lines above will let hibernate know that you want to join on this table and bring the property data along with the Entity data.

I hope I’ve been clear and concise enough. If not, feel free to let me know, I’ll be happy to read and improve upon your comments!

--

--