如何防止基于数据库连接url自动生成Hibernate架构



如何防止基于属性文件中配置的db连接url自动生成Hibernate架构?

我们在spring-boot应用程序中的application.yaml文件中配置了以下代码片段,我们希望根据db连接url值删除并重新创建模式。

这可能吗?

jpa:
generate-ddl: true
show-sql: true
properties:
hibernate:
hbm2ddl:
auto: create-drop

你想做什么?你确定要分析连接url吗?如果你想在dev-env上重新创建模式,而在prod上什么都不做,那么你应该使用概要文件。只需创建application-dev.yaml和application-prod.yaml,并使用-Dspring.profiles.active=dev运行应用程序。

您也可以在yaml文件中使用变量:

properties:
hibernate:
hbm2ddl:
auto: ${generate-schema}

并设置变量,请在此处阅读更多信息https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/html/boot-features-external-config.html

但是,如果您确定要分析连接字符串,可以使用java代码:以编程方式在springboot中设置hibernate.ddl-auto使用编程配置休眠,启动Hibernate.hbm2ddl.auto

请检查此答案

您可以在行中添加条件检查

原始答案

@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");

最新更新