What happens when the following programmatic transaction and session idiom is used with within CMT (EJB3) and Hibernate Core is set up to use CMT?
Assumed a current CMT transaction is required and started using default @TransactionAttribute(REQUIRED)
- Will the hibernate transaction join the current CMT on
beginTransaction()
? - Will
commit()
try to commit the hibernate transaction immediately or wait until the current CMT commits? - What happens when closing the session in CMT?
B. Does the behavior depends if the current-session is bound to CMT using getCurrentSession()
?
// A: openSession()
// B: getCurrentSession();
Session session = sessionFactory.openSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
// do some work
tx.commit();
}
catch (final RuntimeException e)
{
try
{
tx.rollback();
}
catch (final RuntimeException e)
{
// log error
}
throw e;
}
finally
{
session.close();
}
In my application currently i am using a single database and it worked fine using programmatic JDBC transactions with Hibernate. Now the application also uses a JMS-Queue for Mail messaging and would like to merge it into the global CMT transaction.
Edit:
At the moment i am not using EntityManager in the application at all and also would like to keep code portable to non-managed environments.
Hibernate configuration hibernate.cfg.xml
to enable CMT:
Hibernate 4.2.6 and Glassfish 3.1.2
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.autocommit">false</property>
<property name="hibernate.connection.datasource">jdbc/datasource</property>
<property name="hibernate.current_session_context_class">jta</property>
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.CMTTransactionFactory</property>
<property name="hibernate.transaction.jta.platform">org.hibernate.service.jta.platform.internal.SunOneJtaPlatform</property>
SessionFactory retrieval
SessionFactory is build within an singleton EJB. Stripped unnecessary stuff.
@Startup
@Singleton
public class SessionManager
{
private SessionFactory sessionFactory;
public SessionManager()
{
final Configuration configuration = new Configuration().configure();
this.sessionFactory = configuration.buildSessionFactory();
}
}