Option 2 through EntityManager If you use Hibernate >= 4.3 and JPA >= 2.0 then you can accces the Session from the EntityManager through <T> T EntityManagar#unwrap(Class<T> cls) . From the Session you can obtain the SessionFactory .
Session is a hibernate-specific API, EntityManager is a standardized API for JPA. You can think of the EntityManager as an adapter class that wraps Session (you can even get the Session object from an EntityManager object via the getDelegate() function).
You can give an object access to an EntityManager instance by using the @PersistenceUnit annotation to inject an EntityManagerFactory , from which you can obtain an EntityManager instance.
The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
To be totally exhaustive, things are different if you're using a JPA 1.0 or a JPA 2.0 implementation.
With JPA 1.0, you'd have to use EntityManager#getDelegate()
. But keep in mind that the result of this method is implementation specific i.e. non portable from application server using Hibernate to the other. For example with JBoss you would do:
org.hibernate.Session session = (Session) manager.getDelegate();
But with GlassFish, you'd have to do:
org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession();
I agree, that's horrible, and the spec is to blame here (not clear enough).
With JPA 2.0, there is a new (and much better) EntityManager#unwrap(Class<T>)
method that is to be preferred over EntityManager#getDelegate()
for new applications.
So with Hibernate as JPA 2.0 implementation (see 3.15. Native Hibernate API), you would do:
Session session = entityManager.unwrap(Session.class);
See the section "5.1. Accessing Hibernate APIs from JPA" in the Hibernate ORM User Guide:
Session session = entityManager.unwrap(Session.class);
This will explain better.
EntityManager em = new JPAUtil().getEntityManager();
Session session = em.unwrap(Session.class);
Criteria c = session.createCriteria(Name.class);
'entityManager.unwrap(Session.class)' is used to get session from EntityManager.
@Repository
@Transactional
public class EmployeeRepository {
@PersistenceContext
private EntityManager entityManager;
public Session getSession() {
Session session = entityManager.unwrap(Session.class);
return session;
}
......
......
}
Demo Application link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With