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

Hibernate 6/JPA如何用固定值更新smallint类型列?

问题

升级到Spring Boot 3(对应Hibernate 6.1)后,执行JPQL更新语句时出现类型不匹配错误:原语句更新short类型列时,数值1被识别为Integer类型,触发SemanticException。尝试在JPQL中强制转换((short)1)无效。

原更新语句:

@Modifying
@Query("update Entity set smallintCol = 1 where id = :id")
void doUpdate(@Param("id") int id)

尝试无效的写法:

@Modifying
@Query("update Entity set smallintCol = ((short) 1) where id = :id")
void doUpdate(@Param("id") int id)

报错信息:

Caused by: org.hibernate.query.SemanticException: The assignment expression type [java.lang.Integer] did not match the assignment path type [java.lang.Short] for the path [alias_861886687.qtTentativasEnvio] 

实体类列映射:

@Column(name = "qt_tentativas_envio", nullable = false)
private short qtTentativasEnvio;

解决方法

1. 传递short类型参数

将目标值作为short类型参数传入,明确告知Hibernate类型:

@Modifying
@Query("update Entity set smallintCol = :targetValue where id = :id")
void doUpdate(@Param("id") int id, @Param("targetValue") short targetValue);

调用时传入(short)1即可。

2. 使用HQL的cast函数显式转换

利用Hibernate支持的cast函数,将数值转换为数据库对应的smallint类型,Hibernate会自动映射到Java的short:

@Modifying
@Query("update Entity set smallintCol = cast(1 as smallint) where id = :id")
void doUpdate(@Param("id") int id);

3. 使用原生SQL语句

绕过JPQL的类型校验,直接用原生SQL执行更新,PostgreSQL会自动完成数值类型转换:

@Modifying
@Query(value = "update entity set qt_tentativas_envio = 1 where id = :id", nativeQuery = true)
void doUpdate(@Param("id") int id);

内容的提问来源于stack exchange,提问作者Thiago Sayão

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:25:36