Tuesday, March 20, 2012

Persist with JPA: persist(), merge(), remove(), clear(), close() or flush()?

Which JPA method should be used when?
JPA support some methods for working with the persistence manager:
  • persists()
  • merge()
  • remove()
  • flush()
  • close()
What happens during persist() / flush() / close?
On persist() the transient entity is attached to the persistence context, that means the entity has got a connection to the entity manager. This entity is not immediately represented in the database!
E.g. the transaction is rolled back on account of a sql error or an explicitly called rollback, than
the transient entity or changes made to other entities are not stored in the database:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistence");
EntityManager em = emf.createEntityManager();

...
em.getTransaction().rollback();
...

If you want to synchronize in dedicated places in your transaction code, you use flush().
What happens to detached entities on flush()? Nothing.
What happens to persistent entities, which are connected to transient entities? IllegalStateException
What happens to persistent entities, which are connected to detached entities?
The relationship to the detached entity is stored, if the persistent entity is owner of that relationship.

Normally on transaction end the changes made to the entities and new persistent entities will be stored in database by the JPA-provider.

On a close() the entity manager is closed like as on clear() and all entities are not more connected to the entity manager.
Those entities are now in the state detached and will not be synchronized with the database anymore.
To get synchronisation done you use the method merge().
With merge detached entities can put into persistence context again.
During that operation the entity which should be merged will be copied into the persistent entity.
If for a detached entity no persistent entity is found in the current session, the JPA-provider tries
to load the specific entity or if unsuccessfully it will be stored as a new entity.
An entity is removed from persistence context by calling remove() on the specific entity. On transaction end it will be deleted from the database.
If merge() is called on a already deleted marked entity an IllegalArgumentException is thrown.






2 comments:

  1. A motivating discussion is worth comment. I do think that you need to publish more on this topic, it may not be a taboo subject but typically people do not discuss such subjects. To the next! Many thanks!!
    Technology

    ReplyDelete