Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between evict and detach in hibernate?

Tags:

java

hibernate

I'm having a bit of trouble understanding the difference between evict and detach, does evict detach the session anyway, if so what is the difference? I read it removes the object from the second level cache but didn't get it.

like image 807
Zakaria Bouazza Avatar asked Feb 07 '20 11:02

Zakaria Bouazza


2 Answers

The session.evict() or entityManager.detach() method can be used to remove the object from the first-level cache.

why evict entities from the cache?

When the flush() method is called, the state of the entity is saved in the database.You should evict entities if you are processing a huge number of objects and need to manage memory efficiently.

Evicting an entity from the Hibernate Session:

for(Person person : (List<Person>) session.createQuery("select p from Person p")
                     .list()) {
    dtos.add(toDTO(person));
    session.evict( person );
}

Detaching an entity from the EntityManager:

for(Person person : entityManager.createQuery("select p from Person p", Person.class)
        .getResultList()) {
    dtos.add(toDTO(person));
    entityManager.detach( person );
}

If you want to evict the entry from the second-level cache, you can do it following way:

entityManagerFactory.getCache().evict(..);

OR

sessionFactory.getCache().evict(..);

TL;DR detach as well as evict is used to remove the object from 1st level cache

like image 114
Govinda Sakhare Avatar answered Sep 29 '22 18:09

Govinda Sakhare


Actually, EntityManager.detach and hibernate Session.evict do the same thing:

... remove the object and its collections from the first-level cache

From the hibernate implementation of org.hibernate.Session we can see that the detach method make an internal call of the evict method.

public final class SessionImpl {
    // ...
    @Override
    public void detach(Object entity) {
        checkOpen();
        try {
            evict( entity );
        }
        catch (RuntimeException e) {
            throw exceptionConverter.convert( e );
        }
    }
}
like image 33
SternK Avatar answered Sep 29 '22 18:09

SternK