【问题标题】:Implicitly casting bigint postgres datatytpe to Java Long将 bigint postgres 数据类型隐式转换为 Java Long
【发布时间】:2018-05-25 07:57:48
【问题描述】:

我正在使用本机查询来获取bigint 数字列表,然后我计划对其进行迭代。

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

如果我使用如上所示的 Long 数据类型,则会引发以下错误

java.math.BigInteger 不能转换为 java.lang.Long

JPA 似乎默认将 bigint 从数据库转换为 BigInteger。

显然,与 Long 相比,BigInteger 是一个巨大的数据类型。尽管在存储时,我的字段在定义的实体中是 Long 类型,因此,在将 BigInteger 转换回 Long 值时不会丢失数据,还有其他方法可以摆脱 BigInteger 数据类型?更具体地说,我不希望调用 getAllBigIntFieldValues 方法的方法将 BigInteger 显式转换为 LongValue。

【问题讨论】:

  • 关于为什么会发生这种情况的原因,this question 提供了一些见解。

标签: java postgresql java-8 spring-data spring-data-jpa


【解决方案1】:

Spring Data JPA 机制无法做到这一点。

源码相关部分为JpaQueryExecution

它有一个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;

很遗憾,没有将转换器添加到此转换服务的机制。

您可以做的是使用 SQL 的强大功能并将 select 中的值转换为将由底层 JDBC 驱动程序作为 Long 提供的东西。

例如,应该可以在 MySQL 中将结果转换为 UNSIGNED BIGINT and get a Long

刚刚注意到您在标题中提到了 Postgres。 BIGSERIAL might be an option there.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    相关资源
    最近更新 更多