我正在使用 native 查询来获取 bigint
数字列表,然后我计划对其进行迭代。
@Query(value="SELECT bigint_field FROM complex_innerquery", nativeQuery=true)
Collection<Long> getAllBigIntFieldValues();
如果我使用如上所示的 Long 数据类型,它会抛出以下错误
java.math.BigInteger cannot be cast to java.lang.Long
似乎 JPA 默认将 bigint 从数据库转换为 BigInteger。
显然,与 Long 相比,BigInteger 是一个巨大的数据类型。虽然在存储时,我的字段在定义的实体中是 Long 类型,因此在从 BigInteger 转换回 Long 值时不会丢失数据,但有没有其他方法可以摆脱 BigInteger 数据类型?更具体地说,我不希望调用 getAllBigIntFieldValues
方法的方法显式地将 BigInteger 转换为 LongValue。
最佳答案
你不能用 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 的强大功能并将选择中的值转换为将由底层 JDBC 驱动程序作为 Long 提供的值。
例如,在 MySQL 中应该可以将结果转换为 UNSIGNED BIGINT
and get a Long
。
刚刚注意到您在标题中提到了 Postgres。 BIGSERIAL might be an option there .
关于java - 将 bigint postgres 数据类型隐式转换为 Java Long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47758953/