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

ThunderPhoenix picture ThunderPhoenix · Aug 29, 2013 · Viewed 15.7k times · Source

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.

Answer

JGutierrezC picture JGutierrezC · Aug 29, 2013
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!