Chapter 5. Hibernate Integration

5.1. Hibernate Mapping Files

Persistent classes that are mapped using Hibernate .hbm.xml files are supported. The EJB3 Deployer will search the archive for any .hbm.xml files and add them to the definition of the underlying Hibernate SessionFactory. These .hbm.xml files can be virtually anywhere within the archive under any java package or directory.

Class Mappings defined in .hbm.xml files can be managed by EntityManagers just as annotated @Entity beans are. Also, you are allowed to have relationships between a .hbm.xml mapped class and an EJB3 entity. So, mixing/matching is allowed.

5.2. Injection Hibernate Session and SessionFactory

You can inject a org.hibernate.Session and org.hibernate.SessionFactory directly into your EJBs just as you can do with EntityManagers and EntityManagerFactorys. The behavior of a Session is just the same as the behavior of an injected EntityManager. The application server controls the lifecycle of the Session so that you do not have to open, flush, or close the session. Extended persistence contexts also work with injected Hibernate Sessions.

import org.hibernate.Session;
import org.hibernate.SessionFactory;

@Stateful public class MyStatefulBean ... {
   @PersistenceContext(unitName="crm") Session session1;
   @PersistenceContext(unitName="crm2", type=EXTENDED) Session extendedpc;
   @PersistenceUnit(unitName="crm") SessionFactory factory;
         
}
      

5.3. Access to org.hibernate.Session

You can get access to the current underlying Hibernate Session by typecasting your reference to EntityManager.

       @PersistenceContext EntityManager entityManager;
       public void someMethod();
       {
         org.jboss.ejb3.entity.HibernateSession hs = (HibernateSession)entityManager;
         org.hibernate.Session session = hs.getHibernateSession();
       }
      

5.4. Access to org.hibernate.Query

You can get access to the current underlying Hibernate Query by typecasting your reference to a org.hibernate.ejb.QueryImpl.

       @PersistenceContext EntityManager entityManager;
       public void someMethod();
       {
         javax.persistence.Query query = entityManager.createQuery(...);
         org.hiberante.ejb.QueryImpl hs = (QueryImpl)query;
         org.hibernate.Query hbQuery = hs.getHibernateQuery();
       }