Search code examples
javahibernatejbossjndijta

Hibernate via JNDI JBoss 6 - Correctly done?


I've setup hibernate via JNDI in JBoss 6.0.0.Final by following alot of articles and had some problems but got it sorted and it works, but the question is, have I done this right? for one I have not specified a transaction lookup or factory class.

service-hibernate.xml file:

<hibernate-configuration xmlns="urn:jboss:hibernate-deployer:1.0">
<session-factory name="java:/hibernate/SessionFactory" bean="jboss.test.har:service=Hibernate, testcase=TimersUnitTestCase">
    <property name="datasourceName">java:jdbc/MyDataSourceDS</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <property name="cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
    <property name="current_session_context_class">jta</property>
    <depends>jboss:service=Naming</depends>
    <depends>jboss:service=TransactionManager</depends>
</session-factory>

Obviously have my entities and .hbm.xml files as well, so here's some code that I'm using in servlet to test with:

UserTransaction utx = (UserTransaction)new InitialContext().lookup("UserTransaction");
utx.begin();
InitialContext ctx = new InitialContext();
SessionFactory sf = (SessionFactory)ctx.lookup("java:/hibernate/SessionFactory");
Session session = sf.getCurrentSession();
List<TblSettings> settings = session.createQuery("FROM TblSettings").list();
utx.commit();

The above code works, but am I doing it the way it was intended?

btw, I'm using the maven HAR plugin the package my entities+.hbm.xml and service-hibernate.xml as a HAR archive.

Thanks.


Solution

  • I believe you are not correctly using Hibernate with JBoss JTA, but Hibernate may be automatically consuming existing JTA transactions. To make sure, try to increase the logging verbosity (just for org.hibernate.transaction should be enough) for Hibernate and look for entries like this:

    16:27:11,518  INFO TransactionFactoryFactory:58 - Using default transaction strategy (direct JDBC transactions)
    16:27:11,520  INFO TransactionManagerLookupFactory:79 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
    

    If you see entries like the above, then you'll need to explicitly set the property transaction.factory_class to org.hibernate.transaction.JTATransactionFactory and the property jta.UserTransaction to java:comp/UserTransaction in your cfg.xml.

    One more thing to note is that HAR deployments were useful in the pre-JPA days, when there was no standard way of using Hibernate in a AS-managed way. HAR deployments will probably be deprecated in JBoss AS 7. You should decide by yourself based on your project, but I'd recommend to consider migrating to JPA for the long term.