简体   繁体   English

将bigint postgres datatytpe隐式转换为Java Long

[英]Implicitly casting bigint postgres datatytpe to Java Long

I am using a native Query to obtain a list of bigint numbers which I then plan to iterate. 我使用本机查询来获取bigint数字列表,然后我计划迭代。

@Query(value="SELECT bigint_field FROM complex_innerquery", nativeQuery=true)
Collection<Long> getAllBigIntFieldValues();

If I use the Long datatype as shown above, it throws the following error 如果我使用如上所示的Long数据类型,则会引发以下错误

java.math.BigInteger cannot be cast to java.lang.Long java.math.BigInteger无法强制转换为java.lang.Long

It seems like JPA converts bigint from database into BigInteger by default. 似乎JPA默认将bigint从数据库转换为BigInteger。

Clearly, BigInteger is a giant datatype compared to Long. 显然,与Long相比,BigInteger是一种巨大的数据类型。 Although, while storing, my field is of type Long in the entity defined and therefore, there is no chance of losing data while doing the conversion from BigInteger back to Long value, is there any other way by which I can get rid of BigInteger datatype? 虽然,在存储时,我的字段在定义的实体中是Long类型,因此,在从BigInteger转换回Long值时没有丢失数据的机会,有没有其他方法可以摆脱BigInteger数据类型? More specifically, I don't want the methods calling getAllBigIntFieldValues method to explicitly convert BigInteger to LongValue. 更具体地说,我不希望调用getAllBigIntFieldValues方法的方法显式地将BigInteger转换为LongValue。

You can't do this with Spring Data JPA mechanics. 使用Spring Data JPA机制无法做到这一点。

The relevant part of the source code is JpaQueryExecution 源代码的相关部分是JpaQueryExecution

It has a ConversionService and tries to use it to convert the query result to the required type: 它有一个ConversionService并尝试使用它将查询结果转换为所需的类型:

if (void.class.equals(requiredType) || requiredType.isAssignableFrom(result.getClass())) {
    return result;
}

return CONVERSION_SERVICE.canConvert(result.getClass(), requiredType) //
        ? CONVERSION_SERVICE.convert(result, requiredType) //
        : result;

Unfortunately, there is no mechanism to add converters to this conversion service. 遗憾的是,没有机制可以将转换器添加到此转换服务。

What you could do though is to use the power of SQL and convert the value in the select into something that will be offered as a Long by the underlying JDBC driver. 你可以做的是使用SQL的强大功能,并将select中的值转换为底层JDBC驱动程序将作为Long提供的内容。

For example it should be possible in MySQL to convert the result to an UNSIGNED BIGINT and get a Long 例如,在MySQL中应该可以将结果转换为UNSIGNED BIGINT并获得Long

Just noted you mentioned Postgres in the title. 刚刚提到你在标题中提到了Postgres。 BIGSERIAL might be an option there . BIGSERIAL可能是一个选择

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM