Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

PersistenceContext & EntityManager Basics

 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys,

Just thought of sharing my understanding on the PersistenceContext & EntityManager with the help of an example below. I have written down in steps what happens in the background when running this example. I hope it will make things clear for others who are trying to understand or rather prepare for the SCBCD certification. The example just illustrates the container managed transaction scoped entity manager / persistence context



The saveMe method has by default Required as the transaction attribute. So at Line 1, the first time an entity manager operation is being performed, the persistence provider checks if there is a transaction already available. Here it is available, then it checks if there is already a PersistenceContext available in this transaction. Since this is the first call to the API, there is no PersistenceContext yet associated with this transaction. So a PersistenceContext is created and is marked as propogated and is then associated with the transaction. At Line 2, the same check happens again but this time we already have a PersistenceContext associated with this current transaction, so it is re-used (as per the JPA specification, only one PersistenceContext can exist in a transaction). At Line 4, the call to persist will mark or rather queue up the changes to be synchronized to the database. After the method call returns the transaction is commited and the changes in the PersistenceContext are synchronized to the database and the PersistenceContext is discarded.

Hope this is to some extend understandable. I will expand this furthur by discussion on extended PersistenceContext and differentiating between a JTA and a Resource Local transactions.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic