Search code examples
hibernatejboss7.xjava-ee-6cdiejb-3.1

Injecting hibernate Session (not EntityManager) into DAO (with JEE6)


I'm trying to inject hibernate Session into DAO. The DAO is injected into a EJB 3.1 Stateless Bean with CDI.

I don't want to use EntityManager. I prefer Hibernate Session directly. But using with EJB, the application server (JBoss 7) try to inject EntityManager, not hibernate Session.


And I'm getting the follow error when the DAO is creating:

Caused by: java.lang.IllegalArgumentException: Can not set org.hibernate.Session field com.mycompany.persistence.dao.RoleDAO.session to org.jboss.as.jpa.container.TransactionScopedEntityManager


My codes:

persistence.xml

<persistence>
    <persistence-unit name="MyPU">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>java:jboss/datasources/MyDS</jta-data-source>

        <class>com.mycompany.entity.MyEntity</class>
        <class>com.mycompany.entity.OtherEntity</class>

        <properties>
            <property name="hibernate.show_sql" value="false" />
        </properties>

    </persistence-unit>
</persistence>


RoleBean.java (the EJB)

@Stateless
@Remote(RoleRemote.class)
public class RoleBean implements RoleRemote {
    @Inject
    private RoleDAO roleDAO;

}


RoleDAO.java

@Named
public class RoleDAO {

    @PersistenceUnit(unitName = "MyPU")
    private Session session;
}


And the error: Caused by: java.lang.IllegalArgumentException: Can not set org.hibernate.Session field com.mycompany.persistence.dao.RoleDAO.session to org.jboss.as.jpa.container.TransactionScopedEntityManager

Is it possible to inject hibernate Session (not EntityManager) in EJB environment?

Thanks


Solution

  • Certainly not that way. I'm not even sure how you would go about doing it without having to write a bunch of boilerplate to join the transaction and whatnot. My advice is to use EntityManager.getDelegate() and cast it to the Hibernate Session.