Social Media

JPA Lifecycle

In JPA an objects can either be managed or detached. Managed changes will be reflected to the datastore, and detached changes wont be reflected in the datastore

This is best illustrated through the Persistence Manager Lifecycle –



  • Read in current persistence context – tracks changes and object identity
  • Changes reflected to datastore
  • If the same object read again in same context – then == applies
  • Not managed by more than one Persistence Context
  • Managed should only reference managed objects

An object becomes managed by –

  • EntityManager.persist() on new object
  • EntityManager.merge() on detached object


  • Not managed by current persistence context
  • Changes not reflected to datastore
  • Should only reference detached objects

An object becomes detacted by –

– new object detached until persist called

  • EntityManager.detach()
  • EntityManager.close()
  • EntityManager.remove()
  • EntityManager.flush()

In coding terms –

[sourcecode lang=”java”] MyEntity e = new MyEntity();

// scenario 1
// tran starts
// tran ends, and the row for someField is updated in the database

// scenario 2
// tran starts
e = new MyEntity();
// tran ends but the row for someField is not updated in the database
// (you made the changes *after* merging)

// scenario 3
// tran starts
e = new MyEntity();
MyEntity e2 = em.merge(e);
// tran ends and the row for someField is updated
// (the changes were made to e2, not e)

Thanks to stackoverflow for this example

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 or on my consultancy website Glendevon Software

follow me on:

Leave a Comment: