[英]Postgres / hibernate operator does not exist: text = bytea
[英]ERROR: operator does not exist : boolean = bytea in spring jpa query and postgres
当我直接在 postgres 中执行以下查询时,它工作正常,但是当我使用 JPA 运行时,会发生以下错误。
示例查询:
select
*
from
products
where
clientId = :clientId
and ((:status is null
and status in (true,
false))
or status = :status)
and ((:anotherStatus is null
and anotherStatus in (true,
false))
or anotherStatus = :anotherStatus);
错误:
错误 org.hibernate.engine.jdbc.spi.SqlExceptionHelper - 错误:运算符不存在:boolean = bytea 提示:没有运算符匹配给定的名称和参数类型您可能需要添加显式类型转换。
在 JPA 中配置如下:
@Query(value="select * from products where clientId = :clientId and ((:status is null and status in (true, false)) or status = :status) and ((:anotherStatus is null and anotherStatus in (true, false)) or anotherStatus = :anotherStatus)",nativeQuery=true)
List<Products> fetchProducts(@Param("clientId") Long clientId, @Param("status") Boolean status, @Param("anotherStatus") Boolean anotherStatus);
基本上我想要实现的是,当用户将参数作为true
过滤器产品发送时,具有true
(活动)或false
(活动),并且当用户不发送任何东西(即null
)然后获取所有产品( true
和false
)
Keep in mind that null = null
, true = null
and false = null
all evaluate to null
, which is treated as false
in a where
-clause. 如果您还有其他需要,请重新表述您的问题。 让我们看一下(:status is null and status in (true,false)) or status =:status
的真值表。
|-------------|-------------|-------------|
| :status | status | result |
|-------------|-------------|-------------|
| null | null | false |
| null | true | true |
| null | false | true |
| true | null | false |
| true | true | true |
| true | false | false |
| false | null | false |
| false | true | false |
| false | false | true |
|-------------|-------------|-------------|
换句话说,您需要一个在status
为null
时始终返回false
的子句。 这在:status
为null
时为true
,如果:status
和status
具有相同的值,则为真。
status is not null and (:status is null or status =:status)
或者,
status is not null and coalesce(:status, status) = status
请注意,对于您描述的错误,这仍然失败,因为当您在 Java 中传递null
时,Hibernate 将:status
绑定为BYTEA
。 您可以通过双重转换来解决此问题。
CAST(CAST(:status AS CHARACTER VARYING) AS BOOLEAN)
如果这是您的意图,则生成的查询将是:
SELECT *
FROM products
WHERE status IS NOT NULL
AND anotherStatus IS NOT NULL
AND COALESCE(CAST(CAST(:status AS CHARACTER VARYING) AS BOOLEAN), status) = status
AND COALESCE(CAST(CAST(:anotherStatus AS CHARACTER VARYING) AS BOOLEAN), anotherStatus) = anotherStatus
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.