I was told that if I create Custom Datasource as shown below that Hibernate will no longer automatically recreate Tables since spring.jpa.hibernate.ddl-auto is being ignored. How can I configure it to recreate Tables for Custom Datasource?
Full application code can be found at GutHub https://github.com/ivoronline/springboot_db_datasource_create_entitiymanager
application.properties
# ORACLE DB
my.spring.datasource.url = jdbc:oracle:thin:@localhost:1522/orcl
my.spring.datasource.username = TEST
my.spring.datasource.password = LETMEIN
# HIBERNATE
spring.jpa.hibernate.ddl-auto = create
spring.jpa.generate-ddl = true
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create works for primary (spring) data source
For using it for another datasource need to create 3 custom bean for set hibernate properties:
@Configuration
public class CustomDataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "my.spring.datasource")
public DataSource customDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public LocalContainerEntityManagerFactoryBean customEntityManagerFactory(
@Qualifier("customDataSource") DataSource customDataSource,
HibernateProperties hibernateProperties) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(customDataSource);
em.setPackagesToScan("com.stackoverflow.entites"); // Set the package to scan for entities
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
new HashMap(), new HibernateSettings());
properties.put("hibernate.hbm2ddl.auto", "create"); // Customize the ddl-auto setting here
em.setJpaPropertyMap(properties);
return em;
}
@Bean
public JpaTransactionManager customTransactionManager(
@Qualifier("customEntityManagerFactory") EntityManagerFactory customEntityManagerFactory) {
return new JpaTransactionManager(customEntityManagerFactory);
}
}