Search code examples
javaspringhibernatejpa

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?


Solution

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