13

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.

ThunderPhoenix
  • 1,649
  • 4
  • 20
  • 47
  • Basically, you will use detach when you want to make some more sanity checks on that object, or you will keep using that instance some time before committing it. This way - keeping it detached - you will not overload the underlying implementation of the JPA (eg. Hibernate) that is handling your persistence. Useful info can be found here: https://stackoverflow.com/questions/21622841/why-need-detached-entities-in-jpa – Victor Apr 09 '20 at 10:45
  • Or when you want to be sure that when requested again, the object returned will be the new updated one. Otherwise, the EntityManager may return you the cached one. – Victor Apr 10 '20 at 08:36

1 Answers1

23
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!

JGutierrezC
  • 4,398
  • 5
  • 25
  • 42
  • What will happen to the removed object in second case? Will it become detaches? Is it save to manipulate the object afterwards as a regular object? – Zveratko Nov 27 '18 at 08:20