This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes EJB Certification (SCBCD/OCPJBCD) and the fly likes PersistenceContext & EntityManager Basics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » EJB Certification (SCBCD/OCPJBCD)
Bookmark "PersistenceContext & EntityManager Basics" Watch "PersistenceContext & EntityManager Basics" New topic

PersistenceContext & EntityManager Basics

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 10033


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.

SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
I agree. Here's the link:
subject: PersistenceContext & EntityManager Basics
It's not a secret anymore!