Hibernate version: 3.2.1 GA, EntityManager
Application Server: Websphere Version 6.1, CMT
Database: Oracle 10g
Using Stateless Session bean (EJB 2.1) /CMT with Hibernate’s EntityManager
Hi all,
if I instantiate HEM twice in the same transaction I get different mapped sessions so that changing data via the first EM isn't propagated to the second one (helper class and configuration see on bottom of this posting).
Here is my test case:
Code:
/*
* transaction-attribute set to REQUIRED
*/
public void myRemoteTestMethod() {
A a = new A(); // with id as pk
// some modifications
JpaUtil.getEntityManager("TestUnit").persist(a);
AssertNotNull(findA(a));
}
private A findA(A a) {
return JpaUtil.getEntityManager("TestUnit").find(A.class, a.getId());
}
I expected to get two instances of the EM mapping to the same PersistenceContext (Session) but this isn't so.
I debugged the HEM creation and found usage of SessionFactory::openSession().
On the other side I found hints in the community to use sessionfactory.getCurrentSession() under CMT for work without EM.
A solution offered by the community is the usage of entity manager via a ThreadLocal.
But this is dangerous because threads are reused by a thread pool ??
Another solution is to insert an explicite flush() before calling child method. This works because the physical db connection seems to be the same.
But this is not that what I really want to do.
Any suggestions ??
Thanks a lot for all replies
Tom
Hibernate Configuration Code:
<persistence-unit name="TestUnit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/MyDataSource</jta-data-source>
<properties>
<property name="hibernate.archive.autodetection" value="class, hbm"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.session_factory_name" value="MyProject/SessionFactory"/>
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WebSphereTransactionManagerLookup"/>
</properties>
</persistence-unit>
Hibernate helper class Code:
public class JpaUtil {
private static Map<String, EntityManagerFactory> factories = new HashMap<String, EntityManagerFactory>();
/**
* Returns the Entity manager to use.
*
* @return Configuration
*/
public static EntityManager getEntityManager(String persistenceUnit) {
return getEntityManager(persistenceUnit, new HashMap());
}
public static EntityManager getEntityManager(String persistenceUnit, Map overwrite) {
EntityManagerFactory emf = factories.get(persistenceUnit);
if (emf == null) {
emf = Persistence.createEntityManagerFactory(persistenceUnit, overwrite);
factories.put(persistenceUnit, emf);
}
EntityManager manager = emf.createEntityManager();
manager.setFlushMode(FlushModeType.AUTO);
return manager;
}