PostgreSQL, Spring Data JPA: Integer null 解释为 bytea

Joh*_*gel 5 postgresql hibernate spring-data-jpa

在 PostgreSQL 我有表

CREATE TABLE public.my_table
(
    id integer NOT NULL,
    ...
Run Code Online (Sandbox Code Playgroud)

我想执行查询:向我显示具有给定 ID 的行。如果 id 为空,则显示所有行。

我试过了

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);
Run Code Online (Sandbox Code Playgroud)

如果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]
...
Run Code Online (Sandbox Code Playgroud)

显然短路评估不起作用并null转化为bytea

作为一种解决方法,我已将查询值更改为

SELECT * FROM my_table WHERE (?1 IS NULL OR id = (CAST (CAST(?1 AS character varying) AS integer)))
Run Code Online (Sandbox Code Playgroud)

但这并不好,因为 int 被转换为 string 并再次转换为 int。您是否有更好的解决方案,例如更好的强制转换或 sql 查询?

col*_*ict 5

对此的另一种解决方法是从 EntityManager(em在示例中)手动创建查询,并setParameter使用非空值调用一次,然后再次使用真实值调用它。

private static final Integer exampleInt = 1;

List<MyTable> findAll(Integer id) {
    return em.createNativeQuery("SELECT * FROM my_table WHERE (:id IS NULL OR id = :id)", MyTable.class)
            .setParameter("id", exampleInt)
            .setParameter("id", id)
            .resultList();
}
Run Code Online (Sandbox Code Playgroud)

这确保了 Hibernate 在下一次被调用时知道值的类型,即使它是 null。

错误在于 PostgreSQL 服务器,而不是 Hibernate,但他们拒绝修复它,因为它按预期工作。服务器上只有几百种类型的 SQL NULL 并且它们大多彼此不兼容,即使它应该是一个单一的特殊值。