This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of The Little Book of Impediments (e-book only) and have Tom Perry on-line!
See this thread for details.
Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on EntityManager

 
nitin pai
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the JPA specs:


/**
* Create a new EntityManager.
* This method returns a new EntityManager instance each time
* it is invoked.
* The isOpen method will return true on the returned instance.
*/
public EntityManager createEntityManager();


My question is, Shouldn't the EntityManager be a singleton object?

I guess that the EntityManagerFactory is a singleton for a persistance context, but if it can instantiate a new EntityManager everytime createEntityManager() is called, wouldn't it make the database inconsistent if these newly created EntityManagers modify the same data concurrently?
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi nitin,

the API of EntityManagerFactory explicitly says createEntityManager() always returns a new instance. Of course you're right that this could make trouble or lead to inconsistent databases.

And to prevent this you should use transactions where necessary! Transactions for databases are somewhat similar to synchronization for multi-threaded applications. You have to take care to do all database actions which should be atomic within one transaction to avoid inconsistent data.

Be aware that transaction behavior for the JPA is different when used within a container like JBoss or Glassfish in contrast to a standalone application. In a container a transaction by default lasts for the entire method in which you interact with the EntityManager (though this behavior can be configured). In a standalone application you have to do something like this instead:

This will take care that the database within this transaction will be committed as one atomic command. It's the ACID principle for transactions and databases

Marco
[ May 20, 2008: Message edited by: Marco Ehrentreich ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic