Search code examples
hibernateclassloaderhibernate-5.x

hibernate 5 and JPA and setting entity classloader dynamically


I have a web application using a library with a 'CompilingClassLoader' and when it does a reload (because someone edited code), a new classloader is created each time. When that happens, the following code in a hibernate plugin I am writing is executed

@Singleton
@Provides
public EntityManagerFactory providesSessionFactory() throws IOException {
    log.info("Loading Hibernate.  ENTITY classloader="+entityClassLoader+" hibernate classloader="+this.getClass().getClassLoader());
    Map<String, Object> properties = new HashMap<>();
    properties.put("hibernate.classLoader.application", entityClassLoader);
    EntityManagerFactory factory = Persistence.createEntityManagerFactory(persistenceUnit, properties );
    log.info("Done loading Hibernate");
    return factory;
}

The issue occurs because I think "hibernate.classLoader.application" must be instead defined in persistence.xml (which defeats the purpose of what I need since this happens each time a developer changes code).

Basically, we have a development mode in which the CompilingClassLoader keeps changing (it's real fast too so it works great) but I can't figure out how to do this in hibernate right now. Is there a way to set it via some ThreadLocal OR in the Thread.current.setContextClassLoader() somehow.

thanks, Dean


Solution

  • This ended up working

        Collection<ClassLoader> classLoaders = new ArrayList<>();
        classLoaders.add(entityClassLoader);
        Map<String, Object> properties = new HashMap<>();
        properties.put(AvailableSettings.CLASSLOADERS, classLoaders);
    
        EntityManagerFactory factory = Persistence.createEntityManagerFactory(persistenceUnit, properties );