Spring 启动 schema.sql - 重启时删除数据库模式
Spring Boot schema.sql - drop db schema on restart
您好,我正在使用 Spring 引导版本 1.5.9。
当使用 Spring 引导为 mysql 数据库初始化 schema.sql
时,一切正常,数据库模式已成功创建。但是在应用程序重新启动时,这个 schema.sql
脚本再次执行,应用程序无法启动,因为表已经存在。
我尝试了 application.properties
中的 spring.jpa.hibernate.ddl-auto=create-drop
选项,但它没有任何效果(可能是因为它只适用于我没有使用的 Hibernate 实体)
如果数据库不是内存中的数据库,是否有办法让 Spring 每次重新启动时从 schema.sql
引导重新创建架构?
GitHub:
https://github.com/itisha/spring-batch-demo/tree/database-input
关闭自动模式创建以避免冲突:将此行添加到您的 application.properties
spring.jpa.hibernate.ddl-auto=none
一种解决方法是,更改 schema.sql 中的创建语句
来自
CREATE TABLE test .....
至
CREATE TABLE IF NOT EXISTS test ...
使用 IF NOT EXISTS 语句
根据 documentation,您可以通过将 spring.datasource.continue-on-error
属性 设置为 true
来简单地忽略异常
Spring Boot enables the fail-fast feature of the Spring JDBC
initializer by default, so if the scripts cause exceptions the
application will fail to start. You can tune that using
spring.datasource.continue-on-error.
甚至将 spring.datasource.initialize
设置为 false
将其关闭
You can also disable initialization by setting spring.datasource.initialize to false.
您好,我正在使用 Spring 引导版本 1.5.9。
当使用 Spring 引导为 mysql 数据库初始化 schema.sql
时,一切正常,数据库模式已成功创建。但是在应用程序重新启动时,这个 schema.sql
脚本再次执行,应用程序无法启动,因为表已经存在。
我尝试了 application.properties
中的 spring.jpa.hibernate.ddl-auto=create-drop
选项,但它没有任何效果(可能是因为它只适用于我没有使用的 Hibernate 实体)
如果数据库不是内存中的数据库,是否有办法让 Spring 每次重新启动时从 schema.sql
引导重新创建架构?
GitHub: https://github.com/itisha/spring-batch-demo/tree/database-input
关闭自动模式创建以避免冲突:将此行添加到您的 application.properties
spring.jpa.hibernate.ddl-auto=none
一种解决方法是,更改 schema.sql 中的创建语句 来自
CREATE TABLE test .....
至
CREATE TABLE IF NOT EXISTS test ...
使用 IF NOT EXISTS 语句
根据 documentation,您可以通过将 spring.datasource.continue-on-error
属性 设置为 true
Spring Boot enables the fail-fast feature of the Spring JDBC initializer by default, so if the scripts cause exceptions the application will fail to start. You can tune that using spring.datasource.continue-on-error.
甚至将 spring.datasource.initialize
设置为 false
You can also disable initialization by setting spring.datasource.initialize to false.