Damien Beaufils
Damien Beaufils

Reputation: 554

How to specifiy Hibernate mappings with Spring Boot 2.0?

With Spring Boot 1.x, we could specify hibernate mapping files by extending HibernateJpaAutoConfiguration, overriding LocalContainerEntityManagerFactoryBean bean and set mapping resources, like in this answer.

Since Spring Boot 2.0 (2.0.0.M5 precisly), we can’t do this anymore because HibernateJpaAutoConfiguration has changed (with this commit) and we can’t extend the HibernateJpaConfiguration because it is package protected.

Do you know another way to specify hibernate mapping files using Spring Boot 2.0?

Thanks!

Upvotes: 2

Views: 5681

Answers (2)

Balu Sakari
Balu Sakari

Reputation: 1

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

Upvotes: 0

Damien Beaufils
Damien Beaufils

Reputation: 554

Since Spring Boot 2.0.0.M6, rather than overriding Spring Boot's internal, you should use the new spring.jpa.mapping-resources property for defining custom mappings.

Example in YML: spring: jpa: mapping-resources: - db/mappings/dummy.xml

For a complete example, check the application.yml configuration file of this repository.

Upvotes: 7

Related Questions