DEV Community

Vigneshwaralingam
Vigneshwaralingam

Posted on

Have you ever faced the LazyInitializationException-JPA Architecture

Hi everyone..If you understand JPA Architecture, you will understand exactly how data moves from your Java code to the Database tables.

first of all ....What is JPA?

JPA (Java Persistence API) is just a specification (a set of rules).In Spring Boot, when you use JPA, you are internally using Hibernate.

There are 4 Main Components of JPA Architecture

1.Entity

2.EntityManagerFactory

3.EntityManager

4.Persistence Context

Entity:

It is just a simple Java Class with @entity
It represents a single row in a table

EntityManagerFactory:

It create an EntityManager.
It is created only once when your application starts.

EntityManager:

This is the most important part.
It manages the database operations like Save, Update, Delete, Find.
for every 1 Request = 1 EntityManager.

Persistence Context:

This is a temporary memory area inside the EntityManager.
When you fetch a user from the DB, JPA puts it in this place.
If you ask for that user again in the same transaction, JPA gives it from the place, not the Database.
This is why JPA is fast .
but you will get "Lazy Loading" errors when the context is closed.

Data flow:

Your Controller calls the Service, which calls the Repository.
The Repository uses the EntityManager to start a transaction.
The EntityManager checks: "Is this user already in my Memory???
If No: ----- Itis ready to send data to the DB.
If Yes: ------- It updates the object in memory.
then Hibernate takes the Java Object and converts it into a SQL
Hibernate take this SQL to the JDBC driver.
The Database executes the SQL and saves the row.

The Main Feature:

This is the main part of JPA Architecture.Because the EntityManager watches the Persistence Context, you dont always need to call .save().

Example programs:

 @Transactional // 1
public void updateUser(Long id) {
    User user = userRepository.findById(id).get(); //2
    user.setName("Vignesh"); //3   
}
Enter fullscreen mode Exit fullscreen mode
  1. Start Transaction here the EntityManager will Open

  2. User is loaded into Persistence Context .

  3. here we modifd the object in code.The EntityManager sees the object in memory is different from the DB. so it is run the update query in sql...

LazyInitializationException???

Transient: it Just a Java object but not in DB.
Persistent: In the DB and watched by the EntityManager
Detached: In the DB but the transaction closed ,This is where Lazy Loading fails.

So, next time you see a LazyInitializationException, you know exactly what happened: You tried to access data from a Detached object after the EntityManager had already closed its shift.

Top comments (1)

Collapse
 
ranjith_ranjith_6851c8e0a profile image
Ranjith Ranjith

Nice bro