Spring Boot使用Postgres原生查询Hstore键值对报错求助
Postgres Hstore查询报错:operator does not exist: hstore ->> character varying
问题场景
使用Spring Boot原生查询Postgres中的Hstore条目,代码如下:
@Query(value = "select * from result x where x.tenant_id = ?1 AND x.deleted != true AND x.metadata ->> ?2 = ?3", nativeQuery = true)
执行后报错:
Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: hstore ->> character varying
错误原因
Postgres中->>操作符针对hstore类型时,要求右侧参数为text类型,但你传入的?2参数被识别为character varying类型,Postgres未自动完成类型转换,导致找不到匹配的操作符签名。
解决技巧
强制转换参数类型:将第二个参数显式转为text类型,修改查询语句:
@Query(value = "select * from result x where x.tenant_id = ?1 AND x.deleted != true AND x.metadata ->> cast(?2 as text) = ?3", nativeQuery = true)使用hstore专属函数:直接调用Postgres提供的
hstore_get_text函数替代操作符,函数会自动处理类型匹配:@Query(value = "select * from result x where x.tenant_id = ?1 AND x.deleted != true AND hstore_get_text(x.metadata, ?2) = ?3", nativeQuery = true)验证字段类型:确认
metadata字段确实是hstore类型,若误建为jsonb或其他类型,需调整字段类型或使用对应类型的查询语法。
内容的提问来源于stack exchange,提问作者Alex Tbk
相关产品推荐
相关产品推荐

