Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set hibernate.ddl-auto in springboot programmatically

I use springboot in a non web application and data jpa. I use the default configuration except for datasource:

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

How can I set the spring.jpa.hibernate.ddl-auto property also programmatically?

like image 812
Semaphor Avatar asked Dec 11 '15 11:12

Semaphor


1 Answers

Adding the following bean seems to do the job (thanks to Jens' comment):

  @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;
  }
like image 101
Semaphor Avatar answered Oct 03 '22 16:10

Semaphor