whysoseriousson
whysoseriousson

Reputation: 306

Hibernate mapping file location and spring boot

How can I configure hibernate session factory in spring boot. I want to user hbm.xml mapping files and wish to provide class path location. I was not able to find default location from where spring boot can pick up and configure session factory for me. So ultimately I have to do it in the old fashion way, where in I created a bean explicitly. I do believe there has to be an elegant way in spring boot. Please advice.

Upvotes: 0

Views: 2592

Answers (2)

Raymond Chiu
Raymond Chiu

Reputation: 1084

Put them under the src/main/resource folder and the Spring Boot / Hibernate will auto scan all the *.hbm.xml file. If you want to specify in the application.properties, you can define the spring.jpa.mapping-resources property as follows:

spring.jpa.mapping-resources=hibernate/MyMapping.hbm.xml,hibernate/MyMapping2.hbm.xml

Upvotes: 0

Rahul Gupta
Rahul Gupta

Reputation: 520

You can configure hibernate sessionFactory by the following -

@Configuration
@EnableTransactionManagement
@ComponentScan({"com.yourPackageName"})
@PropertySource("classpath:application.properties")
public class HibernateConfiguration {

@Autowired
Environment environment;

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[]{"com.yourPackageName"});
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("database.driverClass"));
    dataSource.setUrl(environment.getRequiredProperty("database.url"));
    dataSource.setUsername(environment.getRequiredProperty("database.username"));
    dataSource.setPassword(environment.getRequiredProperty("database.password"));
    return dataSource;
}

private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
    properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
    return properties;
}

This is the code using in my project to configure hibernate.

Upvotes: 1

Related Questions