The last blog post about the JPA EntityManager didn’t cover the JPA Entity Lifecycle. This post builds on the original one by covering the JPA Entity Lifecycle and associated Lifecycle events
As a reminder the purpose of the EntityManager is to the relationship between the JPA entity and the underlying datasource.
The above diagram shows the 5 key stages of JPA entity management –
MyObject myObject = null;
MyObject myObject = new MyObject();
entityManager.getTransaction().begin(); MyObject myObject = new MyObject(); entityManager.persist(myObject); entityManager.getTransaction().commit();
entityManager.detach(myObject);
entityManager.getTransaction().begin(); entityManager.removed(myObject); entityManager.getTransaction().commit();
The final part of the JPA lifecycle event is the optional callback methods, and their associated annotations –
The pre-methods are executed before the associated method action is executed(ie @PrePersist is executed before em.persist).
The post-methods are executed after the associated method action is executed(ie @PostPerist is executed after em.persist)
If either the pre- or post- methods/annotations throw an exception then the transaction will be rolled back.
The pre- and post- perist methods are useful for setting timestamps for auditing, or set default values.