Social Media
JPA Entity Lifecycle

JPA Entity Lifecycle

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

JPA Entity Lifecycle

JPA Entity Lifecycle

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 –

  • Object Doesnt Exist – This is a null object
  • New Object – Not associated with the EntityManager, and doesnt exist on database
  • Managed – This is the stage were the object becomes persisted and managed by the EntityManager. To do this we need to call the persist method from within a transaction. The object is then persisted to the database when the commit method is called
  • Detached – This state removes the object from the EntityManager, but the object still exists on the database. Some EntityManager methods on a detached object will result in an IllegalArgumentException. The object can be reattached to the EntityManager through the merge method
  • Removed – Deletes the object from the database. Like persist this also needs to take place inside a transaction.

Callback Methods on JPA Entities

The final part of the JPA lifecycle event is the optional callback methods, and their associated annotations –

  • @PrePerist / @PostPersist
  • @PreRemove / @PostRemove
  • @PreUpdate / @PostUpdate
  • @PostLoad

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.

What can you use these Callback events for?

The pre- and post- perist methods are useful for setting timestamps for auditing, or set default values.

 

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training.

You can learn more at About

follow me on:

Leave a Comment:

3 comments
kasyap says 30/08/2017

It is the best tutorial on lifecycle of entities I have ever seen.Thankyou so much to make the things clear.Really Helpful.

Reply
    Martin Farrell says 30/08/2017

    Glad you found the article helpful, and thanks for your kind response

    Reply
Access the EntityManager from Spring Data JPA - javabullets says 03/09/2017

[…] from Spring Data JPA Java 8 Streams Revisited Java 8 Revisited JPA Entity Lifecycle Spring Data REST and […]

Reply
Add Your Reply