我正在构建一个小的spring-boot应用程序。我正在使用spring-data-jpa创建数据库架构,并使用liquibase填充测试数据。
application.properties:
spring.datasource.url=jdbc:postgresql://localhost:5432/book-db
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.username=admin
spring.datasource.password=lTIDDYz3n3jD3BeYaAJz
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
根据文档,如果我在默认路径下具有gradle依赖项和master changeLog,则不需要配置liquibase。
db.changelog-master.yaml:
databaseChangeLog:
- changeSet:
id: 1
author: jb
changes:
- sqlFile:
path: db/migration/insert-books.sql
insert-books.sql:
--liquibase formatted sql
--changeset admin:1
delete from book;
insert into book (id, title)
values (nextval('seq'), 'Functional Programming for Mortals');
commit;
无论有没有commit
,我都尝试过。表databasechangelog
和databasechangelog
已成功创建,并且包含迁移(插入书)。
迁移正在进行,因为如果我向无效的表中添加无效的插入内容,则会出现异常:
ERROR: relation "xxx" does not exist
如何使用liquibase在insert-books.sql脚本中用数据填充数据库?
答案 0 :(得分:1)
不要同时使用liquibase和JPA来管理数据库结构。如果要使用liquibase,请设置JPA(休眠)以仅验证架构并在liquibase中管理架构。
spring.jpa.hibernate.ddl-auto=validate
解决方案的问题在于操作顺序。当您的应用程序启动时,它首先运行liquibase,它会插入数据,然后启动JPA,并从头开始创建模式。
在运行应用程序之前尝试删除架构,我敢肯定迁移(liquibase)会失败。
必须由Liquibase负责架构,有一种方法可以将liquibase添加到现有数据库中,但这又使liquibase成为架构的所有者: