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

SpringBoot+PostgreSQL测试中UUID被识别为bytea的问题求助

解决PostgreSQL中UUID字段被识别为bytea的测试环境问题

问题重现

使用Kotlin+SpringBoot构建REST API,PostgreSQL作为数据库。Postman调用创建User接口正常,但测试环境执行相同操作时抛出错误:

org.postgresql.util.PSQLException: ERROR: column "uuid" is of type bytea but expression is of type uuid

已通过SQL迁移脚本将uuid字段设为UUID类型,但测试环境中该字段仍被识别为bytea。

可能原因及解决方案

1. 验证测试环境表结构正确性

Postman调用正常说明开发/生产环境表结构无问题,但测试环境可能存在以下异常:

  • 测试环境未执行SQL迁移脚本,而是依赖Hibernate自动生成表(如配置spring.jpa.hibernate.ddl-auto=create/update),导致uuid字段被默认映射为bytea。
  • 执行SQL手动检查测试库表结构:
    SELECT data_type FROM information_schema.columns WHERE table_name = 'users' AND column_name = 'uuid';
    
    确保返回结果为uuid而非bytea。如果是bytea,需重新执行迁移脚本,并将spring.jpa.hibernate.ddl-auto设为none,禁用Hibernate自动建表逻辑。

2. 替换兼容的Hibernate方言

旧版org.hibernate.dialect.PostgreSQLDialect对UUID类型的映射存在兼容性问题,会默认将UUID存储为bytea。根据你的PostgreSQL版本替换为对应版本的方言:

  • PostgreSQL 10+:org.hibernate.dialect.PostgreSQL10Dialect
  • PostgreSQL 14+:org.hibernate.dialect.PostgreSQL14Dialect

修改测试环境application.properties:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL14Dialect

3. 实体类明确指定UUID映射类型

在实体类的uuid字段上添加@Type注解,强制Hibernate使用PostgreSQL原生UUID类型映射:

@Entity
@Table(name = "users")
data class UserEntity(

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long,

    @Column(name = "uuid", unique = true, updatable = false, columnDefinition = "uuid")
    @Type(type = "org.hibernate.type.PostgresUUIDType") // 添加此注解
    val uuid: UUID,

    val name: String,

    val password: String,

    @Column(name="created_at")
    val createdAt: LocalDateTime,

    @Column(name="updated_at")
    val updatedAt: LocalDateTime
)

4. 调整JDBC URL参数

在测试环境的JDBC URL中添加stringtype=unspecified参数,让PostgreSQL JDBC驱动正确识别UUID类型:

spring.datasource.url=jdbc:postgresql://localhost:5432/forum?useSSL=false&stringtype=unspecified

5. 确认依赖配置

确保Gradle中PostgreSQL依赖为implementation:

implementation 'org.postgresql:postgresql'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:05:00