You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring项目中R2dbc数据库无法自动初始化问题求助

问题排查与修复方案

1. 依赖版本不兼容(核心问题)

Spring Boot 3.3.4 适配的R2BC PostgreSQL驱动为1.x版本,你当前使用的0.8.13.RELEASE是Spring Boot 2.x的适配版本,版本不匹配会直接导致初始化逻辑失效。同时pom中重复引入了spring-boot-starter-data-r2dbc,需要清理。

修复后的pom依赖片段:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-r2dbc</artifactId>
    </dependency>
    <!-- 无需手动指定版本,Spring Boot parent会自动管理兼容版本 -->
    <dependency>
        <groupId>io.r2dbc</groupId>
        <artifactId>r2dbc-postgresql</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

2. 配置项错误

你的application.yml存在两处无效配置:

  • data: initialization-mode: always是JDBC的初始化配置,R2BC不识别,直接删除。
  • r2dbc节点前存在多余缩进,会导致配置未被正确加载。

修复后的application.yml:

spring:
  r2dbc:
    url: r2dbc:postgresql://localhost:5432/postgres
    username: postgres
    password: admin
    sql:
      init:
        mode: always
  logging:
    level:
      org.springframework: DEBUG
      io.r2dbc: DEBUG

server:
  port: 8088

3. 实体类与数据库映射不匹配

数据库中user_id为SERIAL(整数类型),但实体类中userId定义为String,会导致后续操作报错;同时需显式指定字段映射(PostgreSQL默认使用小写字段名,实体类驼峰需转下划线)。

修复后的UserData实体类:

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "user_data", schema = "management")
public class UserData {
    @Id
    @Column("user_id")
    Integer userId;
    @Column("first_name")
    String firstName;
    @Column("last_name")
    String lastName;
    @Column("email_id")
    String emailId;
    String password;
}

4. 验证初始化逻辑

启动应用后,检查日志中是否出现Executing SQL script from class path resource [schema.sql]的记录,若存在则说明脚本已执行。若仍未创建schema和表,需确认:

  • PostgreSQL服务正常运行,端口、用户名密码无误。
  • 连接的postgres数据库存在,且当前用户拥有创建schema和表的权限。

内容的提问来源于stack exchange,提问作者MoonPie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 06:05:59