hibernate 5 和 JPA 并动态设置实体类加载器

标签 hibernate classloader hibernate-5.x

我有一个使用带有“CompilingClassLoader”的库的 Web 应用程序,当它重新加载时(因为有人编辑了代码),每次都会创建一个新的类加载器。发生这种情况时,将执行我正在编写的 hibernate 插件中的以下代码

@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;
}

出现这个问题是因为我认为必须在 persistence.xml 中定义“hibernate.classLoader.application”(这违背了我需要的目的,因为每次开发人员更改代码时都会发生这种情况)。

基本上,我们有一种开发模式,其中 CompilingClassLoader 不断变化(它也非常快,所以效果很好),但我现在不知道如何在 hibernate 状态下执行此操作。有没有办法通过 Thread.current.setContextClassLoader() 中的一些 ThreadLocal 或以某种方式设置它。

谢谢,
院长

最佳答案

这结束了工作

    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 );

关于 hibernate 5 和 JPA 并动态设置实体类加载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41176863/

相关文章:

java - 在 Hibernate 中只获取最后一条记录,但我想要所有记录

java - 重用类实例而不重新创建它们

java - SpringMvc+ hibernate : Getting NullPointerException in manually inserting data to table

mysql - 如何为以下用例设计表格?

java - 如何在 tomcat 7 上重新部署 hibernate-c3p0 项目而不会出现奇怪的 c3p0 错误

java - Hibernate 5.2 从元模型中获取自然 id 属性

java - hibernate 5 + Java 8 LocalDateTime

java - 用于查找 Java jar 中所有依赖项的工具

java - 带有来自 Jar 的多个 XML 文件的 Spring ApplicationContext

java - 直接 PropertyAccessor 的替代品?