Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Hibernate SessionFactory from JPA's entityManagerFactory

Tags:

hibernate

jpa

I need a specific feature of hibernate that is StatelessSession and for that I need Hibernate's SessionFactory. The problem is I only have the entityManagerFactory. How can I get a StatelessSession in this scenario?

like image 865
ibrabeicker Avatar asked Sep 26 '13 13:09

ibrabeicker


People also ask

How do I get Hibernate SessionFactory from EntityManager?

If a developer uses JPA, there's a neat little trick to get the Hibernate SessionFactory from JPA's EntityManager. First, perform a quick unwrap method call to get the Hibernate Session from the JPA EntityManager. Then call the Hibernate Session's getSessionFactory() method.

What is the difference between EntityManagerFactory manager and SessionFactory?

Using EntityManagerFactory approach allows us to use callback method annotations like @PrePersist, @PostPersist,@PreUpdate with no extra configuration. Using similar callbacks while using SessionFactory will require extra efforts. Related Hibernate docs can be found here and here.

How do I get EntityManager from EntityManagerFactory?

Here's how I would do it (roughly): public class BaseDao{ private static final String PERSISTENCE_UNIT_NAME = "Employee"; private static EntityManagerFactory factory = Persistence. createEntityManagerFactory(PERSISTENCE_UNIT_NAME); public void create(MyEntiy person){ EntityManager em = factory.


3 Answers

Option 1 through EntityManagerFactory

If you use Hibernate >= 4.3 and JPA 2.1 you can accces the SessionFactory from a EntityManagerFactory through <T> T EntityManagarFactory#unwrap(Class<T> cls).

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);

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 session = entityManager.unwrap(Session.class);
SessionFactory sessionFactory = session.getSessionFactory();
like image 130
Paul Wasilewski Avatar answered Oct 02 '22 23:10

Paul Wasilewski


Try to cast EntityManagerFactory to HibernateEntityManagerFactory.

Since EntityManagerFactory doesn't support unwrap() (unlike EntityManager), it seems to be the only way to achieve your goal.

like image 24
axtavt Avatar answered Oct 03 '22 00:10

axtavt


Hibernate >= 4.3 supports JPA 2.1. So you can use EntityManagerFactory.unwrap like emf.unwrap(SessionFactory.class) there.

like image 44
Christian Schneider Avatar answered Oct 02 '22 23:10

Christian Schneider