【发布时间】:2019-05-08 00:00:19
【问题描述】:
在 PostgreSQL 中我有表格
CREATE TABLE public.my_table
(
id integer NOT NULL,
...
我想执行查询:显示给定 id 的行。如果 id 为 null,则显示所有行。
我试过了
public interface MyRepository extends JpaRepository<MyTable, Integer> {
@Query(value = "SELECT * FROM my_table WHERE (?1 IS NULL OR id = ?1)", nativeQuery = true)
List<MyTable> findAll(Integer id);
如果id != null,一切都很好。但是如果id == null,我会收到错误提示
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
...
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
...
Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: integer = bytea
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440) ~[postgresql-42.2.5.jar:42.2.5]
...
显然短路评估不起作用,null 被转换为bytea。
作为一种解决方法,我已将查询值更改为
SELECT * FROM my_table WHERE (?1 IS NULL OR id = (CAST (CAST(?1 AS character varying) AS integer)))
但这并不好,因为 int 被转换为 string 并再次转换为 int。你有更好的解决方案吗,例如更好的演员表或 sql 查询?
【问题讨论】:
标签: postgresql hibernate spring-data-jpa