首页 > 解决方案 > Postgres 类型转换和参数绑定冲突

问题描述

我收到此错误:

org.postgresql.util.PSQLException: No value specified for parameter 1.

对于这种查询:

UPDATE user
 SET Email = 'fake.' || id::varchar || '@localhost'
 WHERE Email is not null and char_length(Email)>0 and removed=false and id in (:ids)

我将此查询作为本机查询运行,如下所示:

        sessionFactory.getCurrentSession()
            .createSQLQuery(sql)
            .setParameterList("ids", ids)
            .executeUpdate()
        ;

似乎id::varchar混淆了 Hibernate 或 JDBC。有什么办法可以逃避这种情况吗?用于类型转换的非常标准的 Postgres 语法。不喜欢强制转换语法,更喜欢使用这种类型映射。

标签: postgresqlhibernatejdbc

解决方案


使用concat()which 将自动转换 ID:

UPDATE user
 SET Email = concat('fake.', id, '@localhost')
 WHERE Email is not null 
   and char_length(Email) > 0 
   and removed = false 
   and id in (:ids)

或者使用标准 CAST 运算符:

UPDATE user
 SET Email = 'fake.' || cast(id as text) || '@localhost'
 WHERE Email is not null 
   and char_length(Email) > 0 
   and removed = false 
   and id in (:ids)

推荐阅读