Spring.sql.init.data-locations 中 DML 失效

来自姬鸿昌的知识库
跳到导航 跳到搜索

# DataSource Config
spring:
  datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
    schema: classpath:db/schema-h2.sql
    username: root
    password: test
    hikari:
      leak-detection-threshold: 2000
      register-mbeans: true
  sql:
    init:
      schema-locations: classpath:db/schema-h2.sql
      data-locations: classpath:db/data-h2.sql
  h2:
    console:
      enabled: true
      path: /h2-console
      settings:
        trace: true

  jpa:
    show-sql: true

为例,启动之后发现 db/data-h2.sql 里 insert 的数据不存在

这是因为 spring.sql.init.schema-locationsspring.sql.init.data-locations 是在 Spring Boot 2.5.0 之后才有的

如果确认当前用的是 Spring Boot 2.5.0 之前的版本就使用 spring.datasource.schemaspring.datasource.data 来配置数据库初始化

spring:
  datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
    schema: classpath:db/schema-h2.sql
    data:
      - classpath:db/data-h2.sql
    username: root
    password: test
    hikari:
      leak-detection-threshold: 2000
      register-mbeans: true
  h2:
    console:
      enabled: true
      path: /h2-console
      settings:
        trace: true

  jpa:
    show-sql: true

https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.5-Release-Notes#sql-script-datasource-initialization