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.
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
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 );
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With