JPA & Spring- how to obtain the shared EntityManager from spring?
I'm using JPA with Hibernate on Spring 3.0.
I have defined a LocalEntityManagerFactoryBean
and JpaTransactionManager
.
All the Daos have an EntityManager
(i guess a shared one开发者_StackOverflow社区) injected with @PersistenceContext
, but i have some code where I'd like to use the same EntityManager
, but fetch it manually. How to accomplish that?
When I just resolve EntityManagerFactory
bean and call createEntityManager
, this EntityManager
is separate from the one which Dao's use (so when i find() and object via DAO, i cannot persist it using manually obtained EntityManager
- entity is detached).
There is one way, but you should be certain that you really need that. In almost all cases you can inject the entity manager.
Here's how to do it if no other option exists:
EntityManagerFactory emf = obtainEntityManagerFactory(); // you mentioned you have it
EntityManagerHolder holder = TransactionSynchronizationManager.getResource(emf);
EntityManager em = holder.getEntityManager();
In short - for each transaction started by the JpaTransactionManager
spring stores the entity manager in a ThreadLocal
, using the factory as a key.
精彩评论