如何解决PostgreSQL自定义枚举类型在Testcontainers中无法使用的问题
问题描述
org.postgresql.util.PSQLException: ERROR: column "status" is of type custom_status but expression is of type character varying
Hint: You will need to rewrite or cast the expression.
在集成测试场景中,通过SpringData仓库向Testcontainers管理的PostgreSQL数据库保存数据时触发上述错误。问题核心是proposal表使用了自定义枚举类型custom_status:
- 真实PostgreSQL数据库搭配官方驱动时,数据保存正常
- 使用Testcontainers的
org.testcontainers.jdbc.ContainerDatabaseDriver连接时,触发类型不匹配错误 - 移除实体类及SQL脚本中的
status字段后,Testcontainers集成测试可正常运行
解决方法
方法一:JDBC URL添加stringtype=unspecified参数
真实环境配置中已通过该参数让PostgreSQL驱动自动适配字符串到自定义枚举类型,只需在Testcontainers配置中同步添加:
修改application-it-test.yml的数据源URL:
spring: datasource: url: jdbc:tc:postgresql:11.6:///databasename?stringtype=unspecified
方法二:配置Hibernate枚举类型映射
若方法一无效,可通过Hibernate注解明确枚举与PostgreSQL自定义类型的映射:
在实体类的status字段上添加@Type注解:
@Entity @Table(name = "proposal") data class Proposal( @Id @Column(name = "proposal_id") val proposalId: String, @Column(name = "amount", nullable = true) val amount: BigDecimal?, @Column(name = "status") @Enumerated(EnumType.STRING) @Type(type = "org.hibernate.type.PostgreSQLEnumType") val status: CustomStatus )
方法三:替换为官方PostgreSQL驱动
放弃Testcontainers的ContainerDatabaseDriver,直接使用官方驱动,通过动态属性注入容器JDBC地址:
1. 修改测试类的动态属性配置
companion object { @Container var postgreSQL: PostgreSQLContainer<*> = PostgreSQLContainer("postgres:11.6") @DynamicPropertySource fun postgreSQLProperties(registry: DynamicPropertyRegistry) { registry.add("spring.datasource.username") { postgreSQL.username } registry.add("spring.datasource.password") { postgreSQL.password } registry.add("spring.datasource.url") { postgreSQL.jdbcUrl } } }
2. 修改application-it-test.yml
spring: datasource: driver-class-name: org.postgresql.Driver type: com.zaxxer.hikari.HikariDataSource hikari: max-lifetime: 500000 connection-timeout: 300000 idle-timeout: 600000 maximum-pool-size: 5 minimum-idle: 1 flyway: enabled: true locations: 'classpath:db/migration/postgresql' jpa: show-sql: true database-platform: org.hibernate.dialect.PostgreSQLDialect
内容的提问来源于stack exchange,提问作者firstpostcommenter
相关产品推荐
相关产品推荐

