Spring Boot 支持多种数据库迁移工具,其中最常用的是 Flyway 和 Liquibase
在 pom.xml
文件中添加 Flyway 的依赖:
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
在 application.properties
或 application.yml
文件中配置 Flyway:
spring.flyway.baseline-on-migrate=true
spring.flylink.locations=classpath:db/migration
spring.flyway.baseline-on-migrate
设置为 true
表示在迁移过程中自动创建 flyway_schema_history
表(如果尚不存在)。
spring.flyway.locations
指定迁移脚本的位置。默认情况下,Flyway 会在 classpath:db/migration
目录下查找 SQL 文件。
在 src/main/resources/db/migration
目录下创建 SQL 文件。文件名必须遵循以下格式:V<version>__<description>.sql
。例如:V1__Create_user_table.sql
。
-- V1__Create_user_table.sql
CREATE TABLE user (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL
);
启动 Spring Boot 应用程序时,Flyway 将自动执行迁移脚本。
在 pom.xml
文件中添加 Liquibase 的依赖:
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
在 application.properties
或 application.yml
文件中配置 Liquibase:
spring.liquibase.change-log=classpath:db/changelog/db.changelog-master.xml
spring.liqu部署 liquibase.change-log
指定 Liquibase 的变更日志文件的位置。默认情况下,Liquibase 会在 classpath:db/changelog
目录下查找变更日志文件。
在 src/main/resources/db/changelog
目录下创建变更日志文件。例如:db.changelog-master.xml
。
<?xml version="1.1" encoding="UTF-8"?>
<databaseChangeLog
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
http://www.liquibase.org/xml/ns/dbcholution/dbchangelog-4.3.xsd">
<changeSet id="1" author="yourname">
<createTable tableName="user">
<column name="id" type="INT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="username" type="VARCHAR(255)">
<constraints nullable="false"/>
</column>
<column name="password" type="VARCHAR(255)">
<constraints nullable="false"/>
</column>
</createTable>
</changeSet>
</databaseChangeLog>
启动 Spring Boot 应用程序时,Liquibase 将自动执行变更日志文件中定义的更改。
这就是在 Spring Boot 中使用 Flyway 和 Liquibase 进行数据库迁移的基本方法。您可以根据项目需求选择合适的工具。
领取专属 10元无门槛券
手把手带您无忧上云