【问题标题】:How to specifiy Hibernate mappings with Spring Boot 2.0?如何使用 Spring Boot 2.0 指定 Hibernate 映射?
【发布时间】:2017-10-17 07:31:21
【问题描述】:

在 Spring Boot 1.x 中,我们可以通过扩展 HibernateJpaAutoConfiguration、覆盖 LocalContainerEntityManagerFactoryBean bean 并设置映射资源 like in this answer 来指定休眠映射文件。

自 Spring Boot 2.0(确切地说是 2.0.0.M5)以来,我们不能再这样做了,因为 HibernateJpaAutoConfiguration 已更改(使用 this commit)并且我们无法扩展 HibernateJpaConfiguration,因为它是包保护的.

您知道使用 Spring Boot 2.0 指定休眠映射文件的另一种方法吗?

谢谢!

【问题讨论】:

标签: spring-boot hibernate-mapping


【解决方案1】:

从 Spring Boot 2.0.0.M6 开始,您应该使用新的 spring.jpa.mapping-resources 属性来定义自定义映射,而不是覆盖 Spring Boot 的内部。

YML 中的示例: spring: jpa: mapping-resources: - db/mappings/dummy.xml

如需完整示例,请查看application.yml configuration file of this repository

【讨论】:

  • 我一直在通过扫描类路径来动态添加映射,而这种方法无法做到这一点。
  • 是否可以使用通配符以便不必在配置中明确列出单个文件?
【解决方案2】:
private String[] loadResourceNames() {
    Resource[] resources = null;
    List<String> names = new ArrayList<String>();

    try {
        resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath: *.hbm.xml");

    
        for ( Resource resource : resources ) {
               names.addAll( Files.list( resource.getFile().toPath() )
                                       .map ( path -> path.getFileName().toString() )
                                       .filter ( p -> p.endsWith( "hbm.xml") )  
                                       .map ( p -> "your directory on class path".concat(p) ) 
                                       .collect ( Collectors.toList() ) );

            }
        }catch(IOException e){
            e.printStackTrace();
        }
    
    System.out.println(resources);
    return names.toArray(new String[names.size()]);
}

@Primary
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,EntityManagerFactoryBuilder builder) {
    Properties properties = new Properties();
    properties.put("hibernate.dialect","org.hibernate.dialect.H2Dialect");
    properties.put("hibernate.format_sql","true");
    properties.put("hibernate.show_sql","true");
    //properties.put("hibernate.current_session_context_class","thread");
    properties.put("hibernate.hbm2ddl.auto","create");
    properties.put("hibernate.ddl-auto","create");
    
    return builder
            .dataSource(dataSource)
            .packages("edu.balu.batch.migration.dataloadccp.model.target")
            .properties(new HashMap(properties))
            .mappingResources(loadResourceNames())
            .build();
}

【讨论】:

  • 嗨,巴鲁。感谢您的回答。通常,提供几句话来解释解决方案可能很有用。
猜你喜欢
  • 2016-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
  • 2015-02-21
  • 1970-01-01
  • 2021-06-28
  • 2018-07-11
相关资源
最近更新 更多