How to prevent the Hibernate schema from being generated automatically based on db connection url configured in properties file?
We have configured below code snippet in application.yaml file in our spring boot application and we want to make schema to be dropped and re-created based on db connection url value.
Is this possible?
jpa:
generate-ddl: true
show-sql: true
properties:
hibernate:
hbm2ddl:
auto: create-drop
CodePudding user response:
What are you trying to do? Are you sure you want to analyze the connection url?
If you want to recreate the schema on dev env, and do nothing on prod, then you should use profiles. Just create application-dev.yaml and application-prod.yaml, and run application with -Dspring.profiles.active=dev
.
You can also use variables in yaml files:
properties:
hibernate:
hbm2ddl:
auto: ${generate-schema}
and set the variable, read more here https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/html/boot-features-external-config.html
But, if you are sure that you want to analyze connection string, you can do in java code: Set hibernate.ddl-auto in springboot programmatically Hibernate using Programmatic Configuration, starting hibernate.hbm2ddl.auto
CodePudding user response:
Please check this answer
You can add a conditional checks in line
Original answer
@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;
}
properties.setProperty("hibernate.hbm2ddl.auto", "update");