Hibernate 6中PostgreSQL UUID字段类型不匹配报错求助
解决Hibernate 6+PostgreSQL嵌入式ID中UUID类型映射报错问题
问题重现
使用Hibernate 6操作PostgreSQL数据库时,嵌入式ID中的UUID字段触发如下报错:
ERROR: column "id" is of type uuid but expression is of type bytea
已尝试@JdbcTypeCode(SqlTypes.UUID)但问题未解决。
解决方案
方案一:为嵌入式ID的UUID字段指定PostgreSQL专属类型处理器
在嵌入式ID的UUID字段上使用@JdbcType注解,指定Hibernate为PostgreSQL实现的UUID专用类型描述器,替代通用的@JdbcTypeCode:
import org.hibernate.type.descriptor.jdbc.PostgresUuidJdbcType; import jakarta.persistence.Embeddable; import java.io.Serializable; import java.util.UUID; import java.util.Objects; @Embeddable public class SomeKey implements Serializable { @JdbcType(PostgresUuidJdbcType.class) private UUID id; private int other; // JPA要求嵌入式ID必须提供无参构造器 public SomeKey() {} public SomeKey(UUID id, int other) { this.id = id; this.other = other; } // 生成getter、setter方法 public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public int getOther() { return other; } public void setOther(int other) { this.other = other; } // 嵌入式ID必须重写equals和hashCode @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SomeKey someKey = (SomeKey) o; return other == someKey.other && Objects.equals(id, someKey.id); } @Override public int hashCode() { return Objects.hash(id, other); } }
方案二:补充数据库连接URL参数
在PostgreSQL的JDBC连接URL中添加stringtype=unspecified参数,强制驱动正确识别UUID类型,避免转为bytea:
jdbc:postgresql://localhost:5432/your_db_name?stringtype=unspecified
关键说明
@JdbcTypeCode(SqlTypes.UUID)采用通用UUID处理逻辑,无法适配PostgreSQL的uuid原生类型;而PostgresUuidJdbcType是Hibernate为PostgreSQL专门实现的类型描述器,能精准映射到数据库的uuid类型。- 嵌入式ID类必须满足JPA规范:实现
Serializable、提供无参构造器、重写equals和hashCode方法,否则可能引发其他隐性问题。
内容的提问来源于stack exchange,提问作者user1432882
相关产品推荐
相关产品推荐

