Hi,
If I use spring to inject an EntityManager instance into a singleton bean, won't it lead to concurrency issues as EM is not thread safe? If not, how does Spring manage to avoid it?
Hi,
If I use spring to inject an EntityManager instance into a singleton bean, won't it lead to concurrency issues as EM is not thread safe? If not, how does Spring manage to avoid it?
I suggest you read the reference gudie explaining spring and JPA.
The spring based EntityManager (which is basically a proxy) is a thread safe one.
Marten Deinum
Java Consultant / Pragmatist / Open Source Enthousiast / Author
Pro Spring MVC: With Web Flow
Conspect
Have you read the reference guide.
Use the [ code ] tags, young padawan
Thanks for the help. It clarified a lot.
Call me stupid, but I don't understand how it is safe to use.
The EntityManager is the JPA version of the Hibernate Session, and a Session is not threadsafe.
@Chandru
But why would you inject a EntityManager in a singleton? In most (all?) cases you want to create a new EntityManager for every transaction (and this can be completely automated by using an transaction aspect).
So am I missing something, or do the provided question and answer make no sense.
blog: http://pveentjer.wordpress.com project: STM Implementation http://multiverse.googlecode.com
I was really unsure about this issue and as a result was planning to implement my Web Services framework (which does not include JEE) using a EntityManagerFactory and have all the service classes get their own EntityManager instance.
Howerver, after stepping into the source code, I discovered that what Spring does is load-time weave the class that needs an EntityManager (I used the @PersistenceContext annotation to indicate injection) with CGLIB. Then on any method invocation of the injected EntityManager, a new EntityManager instance is provided, thereby ensuring that there are no concurrency issues.
You can verify this behavior by adding debug level logging in Log4J for the following package:
org.springframework.orm.jpa
You wll see a message saying "Creating new EntityManager for shared EntityManager invocation" for each method invocation on the EntityManager.
The Spring class that performs the "magic" is org.springframework.orm.jpa.SharedEntityManagerCre ator. If you look at the code, it also closes the EntityManager right after its use.
Last edited by ChrisMuller; Feb 24th, 2009 at 07:50 PM.