如何使用 Spring Boot 2.0 指定 Hibernate 映射?

How to specifiy Hibernate mappings with Spring Boot 2.0?

使用 Spring Boot 1.x,我们可以通过扩展 HibernateJpaAutoConfiguration、覆盖 LocalContainerEntityManagerFactoryBean bean 和设置映射资源 来指定休眠映射文件。

自从 Spring Boot 2.0(准确地说是 2.0.0.M5)以来,我们不能再这样做了,因为 HibernateJpaAutoConfiguration 已经改变(this commit),我们不能扩展 HibernateJpaConfiguration 因为它受包保护。

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

谢谢!

因为 Spring Boot 2.0.0.M6,而不是覆盖 Spring Boot 的内部,你应该使用新的 spring.jpa.mapping-resources 属性 用于定义自定义映射。

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

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

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