Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between 'detach' and 'remove' entityManager's methods

I would like to know what's the real difference between em.detach(entity), em.remove(entity) and using a JPQL request like :

em.createQuery("DELETE FROM Country").exceuteUpdate();

thanks.

like image 710
ThunderPhoenix Avatar asked Aug 29 '13 15:08

ThunderPhoenix


People also ask

What does EntityManager detach do?

detach. Remove the given entity from the persistence context, causing a managed entity to become detached. Unflushed changes made to the entity if any (including removal of the entity), will not be synchronized to the database. Entities which previously referenced the detached entity will continue to reference it.

How does detach operation affect the entity object in new state?

If A is a detached entity, its state is copied into existing managed instance A' of the same entity identity, or a new managed copy of A is created. If A is a new entity, a new managed entity A' is created and the state of A is copied into A' . If A is an existing managed entity, it is ignored.

What is detached object in JPA?

A detached entity (a.k.a. a detached object) is an object that has the same ID as an entity in the persistence store but that is no longer part of a persistence context (the scope of an EntityManager session).


1 Answers

void detach(java.lang.Object entity)

Remove the given entity from the persistence context, causing a managed entity to become detached. Unflushed changes made to the entity if any (including removal of the entity), will not be synchronized to the database. Entities which previously referenced the detached entity will continue to reference it.


void remove(java.lang.Object entity)

Remove the entity instance. The database is affected right away.


em.createQuery("DELETE FROM Country").exceuteUpdate();

Does the Delete directly to database, if you have that object, for example, saved in any list or it is a simple referenced object, it wont get the changes, and surely raise an error if you try to merge, or do something with that. Trust me, don't do a delete like this, unless it is your last choice.

Hope this to be a clear answer!

Best regards!

like image 139
JGutierrezC Avatar answered Sep 24 '22 20:09

JGutierrezC