Search code examples
javahibernatejpaentitymanagersessionfactory

Creating EntityManagerFactory from hibernate Configuration


In our current application (Java SE) we use Hibernate specific API, but we kind of want to migrate to JPA wherever possible (but slowly). For that, I need EntityManagerFactory instead of SessionFactory (and I would like to keep this an axiom without dispute).

Where is the problem is, that currently our session factory is being created from org.hibernate.cfg.Configuration and I would like to keep it as it for now - as this configuration is passed thru different parts of our software which can and do configure the persistence as they want.

So the question is: how can I make

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

equivalent resulting in EntityManagerFactory?


Solution

  • This is quite straightforward. You will need a persistence.xml though, where you have defined a persistence unit for JPA. Then you have to convert the Hibernate properties to a Map, so you can pass them to the createEntityManagerFactory method. This will give you the 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 the SessionFactory from the EntityManagerFactory (the other way around), then you can use this method:

    public SessionFactory getSessionFactory(EntityManagerFactory entityManagerFactory) {
        return ((EntityManagerFactoryImpl) entityManagerFactory).getSessionFactory();
    }