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

时间:2017-10-17 07:31:21

标签: spring-boot hibernate-mapping

使用Spring Boot 1.x,我们可以通过扩展HibernateJpaAutoConfiguration来指定hibernate映射文件,覆盖LocalContainerEntityManagerFactoryBean bean并设置映射资源like in this answer

自Spring Boot 2.0(2.0.0.M5)以来,我们不能再这样做,因为HibernateJpaAutoConfiguration已更改(使用this commit),我们无法扩展{{1}因为它受包保护。

您是否知道使用Spring Boot 2.0指定hibernate映射文件的另一种方法?

谢谢!

2 个答案:

答案 0 :(得分:4)

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

YML中的示例: spring.jpa.mapping-resources

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

答案 1 :(得分:0)

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