以编程方式在springboot中设置hibernate.ddl-auto

时间:2015-12-11 11:54:16

标签: java spring hibernate jpa

我在非Web应用程序和数据jpa中使用springboot。我使用除数据源之外的默认配置:

private static final String dataSourceUrl = "jdbc:h2:./Database;DB_CLOSE_ON_EXIT=FALSE";
@Bean
public DataSource dataSource() {
    return DataSourceBuilder.create().url(dataSourceUrl).username("user").password("pwd").build();
}

如何以编程方式设置spring.jpa.hibernate.ddl-auto属性?

1 个答案:

答案 0 :(得分:7)

添加以下bean似乎可以完成这项工作(感谢Jens的评论):

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource);
    em.setPackagesToScan(new String[] { "packages.to.scan" });

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);

    Properties properties = new Properties();
    properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    properties.setProperty("hibernate.hbm2ddl.auto", "update");
    em.setJpaProperties(properties);

    return em;
  }