JPA & Spring - how to get generic EntityManager from spring?

I am using JPA with Hibernate on Spring 3.0.

I defined a LocalEntityManagerFactoryBean and JpaTransactionManager . All Daos have an EntityManager (I think it's generic) introduced using @PersistenceContext , but I have code in which I would like to use the same EntityManager , but pull it out manually. How to do it?

When I simply enable the EntityManagerFactory bean and call createEntityManager , this EntityManager is separate from the one that Tao uses (therefore, when I find () and the object through the DAO, I cannot save it using the EntityManager manually - the object is disconnected).

+4
source share
1 answer

There is one way, but you must be sure that you really need it. In almost all cases, you can enter an 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 every transaction started by the JpaTransactionManager spring, an object manager is stored in ThreadLocal , using factory as the key.

+4
source

All Articles