首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >postgresql:将bytea转换为bigint

postgresql:将bytea转换为bigint
EN

Stack Overflow用户
提问于 2015-10-05 08:34:35
回答 5查看 12.1K关注 0票数 13

我必须将查询的bytea条目转换为bigint。这是怎么做到的呢?

更多信息:

我有一个hibernate存储库如下所示-

代码语言:javascript
复制
 @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,但是它没有成功,错误信息msg说bytea不能传递给bigint

如何将bytea更改为bigint

编辑:

Sample_Table DAO:

代码语言:javascript
复制
@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字段在这里定义为“长”。

编辑-2如果有人得到这样的问题,他很可能是在查询中传递空值。

EN

回答 5

Stack Overflow用户

发布于 2020-10-16 05:46:34

在存储库查询中,我遇到了这个问题,该查询插入了一个具有可空列的记录。当该列的值为null时,hibernate使用错误的类型,我将看到Postgres中的异常:

代码语言:javascript
复制
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。复制并粘贴它们的片段:

代码语言:javascript
复制
@Query("select * from user where firstname=:name and id=:id", nativeQuery=true)
public List<user> findByNameAndId(@Param("name") String firstName, @Param("id")TypedParameterValue id);
代码语言:javascript
复制
UUID userId = ... //Retrived from request parameter.
TypedParameterValue userIdParam = new TypedParameterValue(new PostgresUUIDType(), userId);
userRepository.findByNameAndId(userName, userIdParam);

不太适合使用Hibernate特定的解决方案,而不是纯JPA解决方案,而是‍♂️。大感谢“碳骑士”或谁添加了这个帖子!

票数 7
EN

Stack Overflow用户

发布于 2016-03-31 09:43:37

除了从适当填充的十六进制字符串中传递位数据类型之外,似乎没有一个简单的函数可以将字节(内存块)转换为基本数据类型:

代码语言:javascript
复制
SELECT ('x'||lpad(encode('\001'::bytea, 'hex'), 16, '0'))::bit(64)::bigint

或者,如果bytea已经是8个字节,并且Postgres安装使用默认设置bytea_output = 'hex'运行,则使用cast to text and remove the leading backslash

代码语言:javascript
复制
SELECT right(bytea_val::text, -1)::bit(64)::bigint
FROM (SELECT '\x0000000000000001'::bytea as bytea_val) x
票数 3
EN

Stack Overflow用户

发布于 2018-05-15 22:02:00

下面的表达式对我有效,可以从bytes::bytea转换为bigint

代码语言:javascript
复制
get_byte(bytes, 0)::bigint << 8
    | get_byte(bytes, 1) << 8
    | get_byte(bytes, 2) << 8
    | get_byte(bytes, 3) << 8
    | get_byte(bytes, 4) << 8
    | get_byte(bytes, 5) << 8
    | get_byte(bytes, 6) << 8
    | get_byte(bytes, 7)

这也正确地处理了符号位。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32944267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档