How to access Hibernate Session in JPA applications?
In order to access Hibernate objects from a JPA application you can use the unwrap method available in the EntityManager and EntityManager Factory class:
EntityManager.<T>unwrap(Class<T>)
EntityManagerFactory.<T>unwrap(Class<T>)
This method can be used to gain access of JPA-vendor-specific classes. For example, here is how you can retrieve Hibernate’s Session and SessionFactory:
Session session = em.unwrap(Session.class);
SessionFactory sessionFactory = em.getEntityManagerFactory().unwrap(SessionFactory.class);
Please note: this method is available since JPA 2.0
JBoss AS 5
If you are running an older application server version (JBoss AS 5), 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();
}
You can also 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();
}
Recommended Articles
Limit Hibernate/JPA Application Result Sets with Native SQL and Pagination
Learn how to optimize your Hibernate/JPA applications by limiting result sets using native SQL and pagination methods.
Learn How to Use Hibernate Connection Properties in persistence.xml for Database Connectivity
Master Hibernate connection settings and configure your persistence.xml file for seamless database connectivity. #Hibernate #JavaPersistence #WildFly
Optimizing Java Persistence with Native Queries and Oracle DB Features
Enhance your Java applications using native queries for Oracle-specific features. Learn how to leverage hierarchical queries in JPA.
Envers Project: Simplify Auditing and Versioning with Hibernate
Simplify auditing and versioning of persistent classes using Envers project in Java. Learn how to use the @Audited annotation for automatic tracking changes. #Hibernate #Java #Audit