Creating an EntityManagerFactory from Hibernate Configuration

In our current application (Java SE), we use the Hibernate API, but we kind of want to switch to JPA, where it is possible (but slowly). To do this, I need an EntityManagerFactory instead of a SessionFactory (and I would like to leave this axiom without argument).

What is the problem: at present, our factory session is created from org.hibernate.cfg.Configuration , and I would like to keep it the same as now, because this configuration is transmitted through various parts of our software that can and do configure persistence by discretion.

So the question is: how can I do

 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() .applySettings( hibConfiguration.getProperties() ) .buildServiceRegistry(); SessionFactory sessionFactory = hibConfiguration.buildSessionFactory( serviceRegistry ); 

what leads to EntityManagerFactory ?

+7
java hibernate jpa entitymanager sessionfactory
source share
1 answer

It is pretty simple. You will need persistence.xml , although you have defined a save block for JPA. Then you need to convert the Hibernate properties to Map so that you can pass them to the createEntityManagerFactory method. This will give you an EntityManagerFactory using your Hibernate properties.

 public EntityManagerFactory createEntityManagerFactory(Configuration hibConfiguration) { Properties p = hibConfiguration.getProperties(); // convert to Map Map<String, String> pMap = new HashMap<>(); Enumeration<?> e = p.propertyNames(); while (e.hasMoreElements()) { String s = (String) e.nextElement(); pMap.put(s, p.getProperty(s)); } // create EntityManagerFactory EntityManagerFactory emf = Persistence.createEntityManagerFactory("some persistence unit", pMap); return emf; } 

If you need a SessionFactory from EntityManagerFactory (vice versa), you can use this method:

 public SessionFactory getSessionFactory(EntityManagerFactory entityManagerFactory) { return ((EntityManagerFactoryImpl) entityManagerFactory).getSessionFactory(); } 
+2
source share

All Articles