You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL原生查询bytea转smallint报错,该如何修复?

修复"column 'code' is of type smallint but expression is of type bytea"错误

核心问题分析

你的代码存在两个关键问题:参数名绑定不匹配,以及Java类型与数据库smallint类型不兼容,二者共同导致了类型解析异常。

修复步骤

1. 修正参数名绑定错误

SQL语句中定义的参数是:httpCode,但setParameter调用时用的是"code",参数名不匹配会让Hibernate无法正确绑定参数,进而默认将其解析为bytea类型,与数据库的smallint类型冲突。同时注意原代码中entity.getCode缺少方法调用括号,需修正为entity.getCode()。

修正后的代码:

entityManager.createQuery(
        "INSERT INTO car(http_code) " +
        "VALUES(:httpCode)")
.setParameter("httpCode", entity.getCode())
.executeUpdate();

2. 确保Java类型匹配数据库smallint

数据库的smallint对应Java的Short类型(取值范围-32768至32767)。如果entity.getCode()返回的是Integer、Byte等其他类型,需要手动转换为Short:

  • 若返回Integer:使用shortValue()方法转换
  • 若返回Byte:直接强制转换为short

示例(假设getCode()返回Integer):

entityManager.createQuery(
        "INSERT INTO car(http_code) " +
        "VALUES(:httpCode)")
.setParameter("httpCode", entity.getCode().shortValue())
.executeUpdate();

3. 移除无效的CAST操作

你之前尝试用CAST转为numeric无效,是因为问题根源不在SQL层面的类型转换,而是参数绑定错误和类型不匹配。修正上述两个问题后,无需额外添加CAST操作。

内容的提问来源于stack exchange,提问作者pawello12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 20:33:28