Spring Boot 全 YAML 配置 Liquibase 教程

发布于:2025-08-04 ⋅ 阅读:(17) ⋅ 点赞:(0)

一、项目初始化配置

1.1 创建 Spring Boot 项目

通过 Spring Initializr 生成基础项目,配置如下:

  • ​Project​​: Maven
  • ​Language​​: Java
  • ​Spring Boot​​: 3.5.3(最新稳定版)
  • ​Project Metadata​​:
    • Group: com.example
    • Artifact: liquibase-demo
    • Package name: com.example.liquibasedemo
  • ​Dependencies​​:
    • Spring Web
    • Spring Data JPA
    • MySQL Driver
    • Liquibase Migration

1.2 项目结构

src
├── main
│   ├── java
│   │   └── com.example.liquibasedemo
│   │       ├── config
│   │       ├── controller
│   │       ├── model
│   │       └── LiquibaseDemoApplication.java
│   └── resources
│       ├── application.yml
│       └── db
│           └── changelog
│               ├── db.changelog-master.yaml
│               └── changes
│                   ├── create-user-table.yaml
│                   └── add-age-column.yaml

二、YAML 配置体系

2.1 数据库连接配置

src/main/resources/application.yml:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/liquibase_demo?useSSL=false&serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: none # 禁用自动 DDL
    show-sql: true
  liquibase:
    change-log: classpath:db/changelog/db.changelog-master.yaml
server:
  port: 8080

2.2 多环境配置(可选)

创建环境专用配置文件:

src/main/resources/
├── application.yml        # 主配置
├── application-dev.yml    # 开发环境
└── application-prod.yml   # 生产环境

激活环境配置:

spring:
  profiles:
    active: dev

三、Liquibase YAML 变更日志

3.1 主变更日志文件

db/changelog/db.changelog-master.yaml:

databaseChangeLog:
  - include:
      file: db/changelog/changes/create-user-table.yaml
      relativeToChangelogFile: true
  - include:
      file: db/changelog/changes/add-age-column.yaml
      relativeToChangelogFile: true

3.2 用户表创建变更集

db/changelog/changes/create-user-table.yaml:

databaseChangeLog:
  - changeSet:
      id: 1
      author: yourname
      changes:
        - createTable:
            tableName: users
            columns:
              - column:
                  name: id
                  type: INT
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: name
                  type: VARCHAR(100)
                  constraints:
                    nullable: false
              - column:
                  name: email
                  type: VARCHAR(100)
                  constraints:
                    unique: true
              - column:
                  name: created_at
                  type: TIMESTAMP
                  defaultValueComputed: CURRENT_TIMESTAMP
                  constraints:
                    nullable: false

3.3 添加年龄列变更集

db/changelog/changes/add-age-column.yaml:

databaseChangeLog:
  - changeSet:
      id: 2
      author: yourname
      changes:
        - addColumn:
            tableName: users
            columns:
              - column:
                  name: age
                  type: INT
                  defaultValue: 18

四、代码集成与验证

4.1 实体类定义

src/main/java/com/example/liquibasedemo/model/User.java:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false)
    private String name;
    
    @Column(unique = true)
    private String email;
    
    @Column(nullable = false)
    private Integer age;
    
    // Getters/Setters
}

4.2 数据操作验证

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
}

4.3 启动验证

mvn spring-boot:run

观察控制台输出:

INFO 12345 --- [           main] l.e.LiquibaseLoggingListener           : Starting Liquibase at 10:00:00 (version 4.23.0)
INFO 12345 --- [           main] l.e.LiquibaseLoggingListener           : ChangeSet db/changelog/changes/create-user-table.yaml::1::yourname executed successfully

五、高级功能实现

5.1 回滚配置

在变更集中添加回滚逻辑:

- changeSet:
    id: 3
    author: yourname
    changes:
      - createTable:
          tableName: orders
          columns:
            - column:
                name: id
                type: INT
                autoIncrement: true
                constraints:
                  primaryKey: true
                  nullable: false
    rollback:
      - dropTable:
          tableName: orders

5.2 条件变更

- changeSet:
    id: 4
    author: yourname
    preConditions:
      - onFail: MARK_RAN
        dbms: mysql
    changes:
      - createIndex:
          tableName: users
          indexName: idx_email
          column:
            name: email

5.3 多环境数据初始化

db/changelog/changes/init-data.yaml:

databaseChangeLog:
  - changeSet:
      id: 5
      author: yourname
      context: dev
      changes:
        - insert:
            tableName: users
            columns:
              - column:
                  name: name
                  value: "Test User"
              - column:
                  name: email
                  value: "test@example.com"
              - column:
                  name: age
                  value: 25

六、最佳实践指南

  1. ​版本控制规范​

    • 使用语义化版本号(如 1.0.0
    • 每个变更集对应单一业务变更
    • 变更集文件按版本顺序编号
  2. ​变更集设计原则​

    - changeSet:
        id: 6
        author: yourname
        changes:
          - sqlFile:
              path: classpath:db/migration/V2__add_address_column.sql
              relativeToChangelogFile: true
  3. ​安全配置​

    spring:
      liquibase:
        contexts: dev
        labels: feature-user-module
        rollbackCount: 3

七、常见问题解决方案

问题现象 解决方案 参考来源
变更集未执行 检查 DATABASECHANGELOG 表记录
YAML格式错误 使用在线YAML验证工具
数据库锁等待 添加 liquibase.lock.timeout=600
多环境冲突 使用 spring.profiles.active 隔离配置

八、完整项目结构示例

liquibase-demo/
├── src/
│   ├── main/
│   │   ├── java/
│   │   └── resources/
│   │       ├── application.yml
│   │       └── db/
│   │           └── changelog/
│   │               ├── db.changelog-master.yaml
│   │               └── changes/
│   │                   ├── create-user-table.yaml
│   │                   └── add-age-column.yaml
├── pom.xml
└── .gitignore

通过本教程,您可以完全使用 YAML 配置实现 Spring Boot 项目的数据库迁移管理。YAML 的层级结构能清晰展现数据库变更历程,配合 Liquibase 的版本控制能力,可有效提升团队协作效率和系统稳定性。


网站公告

今日签到

点亮在社区的每一天
去签到