Man*_*kla 7 postgresql hibernate jpa postgresql-9.1
我必须将查询的bytea条目转换为bigint.怎么可以这样做?
更多信息:
我有一个hibernate存储库,如下所示 -
@Query(value = "update Sample_Table set other_id = ?1 where id = ?2", nativeQuery = true)
void saveOrUpdateOtherId(Long other_id, Long id);
Run Code Online (Sandbox Code Playgroud)
Hibernate以某种方式取id(在where子句中)bytea,因为' Sample_Table '具有此id字段bigint,因此它会抛出类型不匹配问题.
我已经尝试使用CAST转换bytea为bigint但它没有成功,错误msg说bytea无法转换为bigint.
我怎样才能改变bytea来bigint?
编辑:
Sample_Table 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;
}
Run Code Online (Sandbox Code Playgroud)
id field在这里定义为Long.
编辑-2 如果有人遇到这样的问题,他很可能在查询中传递空值.
我在存储库查询中遇到了这个问题,该查询插入了具有可为空列的记录。当该列的值为 null 时,hibernate 使用错误的类型,我会在 Postgres 中看到如下异常:
\ncannot cast type bytea to bigint\nRun Code Online (Sandbox Code Playgroud)\n最终找到了这篇博客文章的解决方案:http://www.carbonrider.com/2020/08/15/org-postgresql-util-psqlexception-error-cannot-cast-type-bytea-to-uuid/ \n这是使用 Hibernate 的TypedParameterValue.\n复制并粘贴其片段:
@Query("select * from user where firstname=:name and id=:id", nativeQuery=true)\npublic List<user> findByNameAndId(@Param("name") String firstName, @Param("id")TypedParameterValue id);\nRun Code Online (Sandbox Code Playgroud)\nUUID userId = ... //Retrived from request parameter.\nTypedParameterValue userIdParam = new TypedParameterValue(new PostgresUUIDType(), userId);\nuserRepository.findByNameAndId(userName, userIdParam);\nRun Code Online (Sandbox Code Playgroud)\n拥有特定于 Hibernate 的解决方案而不是纯粹的 JPA 解决方案并不理想,但是 \xe2\x80\x8d\xe2\x99\x82\xef\xb8\x8f。非常感谢“Carbon Rider”或添加该帖子的任何人!
\n除了从正确填充的十六进制字符串传递位数据类型之外,似乎没有一个简单的函数可以从 bytea(一块内存)转换为基本数据类型:
SELECT ('x'||lpad(encode('\001'::bytea, 'hex'), 16, '0'))::bit(64)::bigint
Run Code Online (Sandbox Code Playgroud)
或者,如果您的 bytea 已经是 8 个字节并且您的 Postgres 安装使用默认设置运行bytea_output = 'hex',则转换为文本并删除前导反斜杠:
SELECT right(bytea_val::text, -1)::bit(64)::bigint
FROM (SELECT '\x0000000000000001'::bytea as bytea_val) x
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2938 次 |
| 最近记录: |