我必须将查询的 bytea 条目转换为 bigint。这是怎么做到的?
更多信息:
我有一个如下所示的 hibernate 存储库 -
@Query(value = "update Sample_Table set other_id = ?1 where id = ?2", nativeQuery = true)
void saveOrUpdateOtherId(Long other_id, Long id);
Hibernate 以某种方式将 id
(在 where 子句中)作为 bytea
,因为“Sample_Table”将此 id 字段作为 bigint
从而引发类型不匹配问题。
我已经尝试使用 CAST 将 bytea
转换为 bigint
但它没有成功并且错误消息说 bytea
无法转换为bigint
。
如何将 bytea
更改为 bigint
?
编辑:
示例_表 DAO:
@Table(name = "Sample_Table")
public class Sample{
@Id
@Column(name = "id", unique = true)
@GeneratedValue
private Long id;
@Column(name = "other_id")
private Long other_id;
}
id
字段在这里定义为 Long。
编辑-2 如果有人遇到这样的问题,很可能他在查询中传递了空值。
最佳答案
我在存储库查询中遇到了这个问题,该查询插入了一个具有可为空列的记录。当该列的值为 null 时,hibernate 使用了错误的类型,我会在 Postgres 中看到这样的异常:
cannot cast type bytea to bigint
最终找到了这篇博文和解决方案:http://www.carbonrider.com/2020/08/15/org-postgresql-util-psqlexception-error-cannot-cast-type-bytea-to-uuid/
这是使用 Hibernate 的 TypedParameterValue
。
复制并粘贴他们的片段:
@Query("select * from user where firstname=:name and id=:id", nativeQuery=true)
public List<user> findByNameAndId(@Param("name") String firstName, @Param("id")TypedParameterValue id);
UUID userId = ... //Retrived from request parameter.
TypedParameterValue userIdParam = new TypedParameterValue(new PostgresUUIDType(), userId);
userRepository.findByNameAndId(userName, userIdParam);
拥有特定于 Hibernate 的解决方案而不是纯粹的 JPA 解决方案并不理想,但是🤷♂️。非常感谢“Carbon Rider”或添加该帖子的人!
关于hibernate - postgresql:将 bytea 转换为 bigint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32944267/