Hibernate映射文件位置和spring boot

时间:2017-09-16 12:38:35

标签: hibernate spring-boot spring-data-jpa

如何在spring boot中配置hibernate会话工厂。我想用hbm.xml映射文件,并希望提供类路径位置。我无法找到弹簧引导可以拾取的默认位置并为我配置会话工厂。所以最终我必须以旧的方式来做,在那里我明确地创建了一个bean。我相信春季靴子必须有一种优雅的方式。请指教。

2 个答案:

答案 0 :(得分:1)

您可以通过以下命令配置hibernate sessionFactory -

@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;
}

这是我的项目中用于配置hibernate的代码。

答案 1 :(得分:0)

将它们放在src / main / resource文件夹下,Spring Boot / Hibernate将自动扫描所有* .hbm.xml文件。 如果要在application.properties中指定,则可以如下定义spring.jpa.mapping-resources属性:

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