postgresql:将bytea转换为bigint

时间:2015-10-05 08:34:36

标签: hibernate postgresql 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);

Hibernate以某种方式将id(在where子句中)作为bytea并且因为' Sample_Table '将此id字段设为bigint,因此它会抛出类型不匹配问题。

我尝试使用CAST将bytea转换为bigint,但未成功,错误信息说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;
}

id字段在此定义为Long。

修改-2 如果有人遇到这样的问题,很可能他在查询中传递空值。

5 个答案:

答案 0 :(得分:1)

除了从正确填充的十六进制字符串中传递位数据类型之外,从bytea(一块内存)转换为基本数据类型似乎不是一个简单的函数:

SELECT ('x'||lpad(encode('\001'::bytea, 'hex'), 16, '0'))::bit(64)::bigint

答案 1 :(得分:1)

您的一个参数是null,无法转换为bigint

答案 2 :(得分:1)

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

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 :(得分:0)

如简·尼尔森所说

您的参数之一为null,无法将其转换为bigint。

您正在尝试在查询中传递null。

答案 4 :(得分:0)

我在存储库查询中遇到了此问题,该查询插入了具有可为空列的记录。当该列的值为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”或添加该帖子的人!

相关问题