gpt4 book ai didi

postgresql - Spring Data JPA 中的错误 : Spring Data returns List instead of List

转载 作者:行者123 更新时间:2023-11-29 11:11:47 25 4
gpt4 key购买 nike

我在 spring-data 上有 DAO 实现:

public interface TestDataRepository extends CrudRepository<DpConfigData, Long> {
@Query(value = "select distinct(oid) from unit", nativeQuery = true)
List<Long> testMethod();
}

单元测试来测试提到的 DAO:

@Test
public void test(){
List<Long> testData = dpConfigDataEntityDataRepository.testMethod();
for (Long oid:testData){
System.out.print(oid);
}
}

运行测试给出奇怪的结果 - List<Long> testData在运行时由 BigInteger 实例填充,而不是由 Long 填充。结果我得到 ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long

JPA 实现 - 休眠。作为数据库,我使用 PostgreSQL,unit.oid字段在 DB 层上具有 BigInt 类型。在获取整个单元的情况下,它被映射到 Long,但是当自定义查询为“select distinct ...”时出了点问题,它被映射到 BigInteger。

那么,我的问题是:这种奇怪行为的原因是什么?如何以优雅的方式解决/解决它?

最佳答案

这是 Spring 数据 JPA 的问题。如果在 DB 中数据类型定义为 BigInteger 并且在 JPA 查询中我们尝试获取 Long 那么它不会给出任何错误,但它在 Long 数据类型中将值设置为 BigInteger。

解决方案:

  1. 使用BigInteger作为返回类型

    @Query(value = "select distinct(oid) from unit", nativeQuery = true)
    List<BigInteger> testMethod();

    然后如下设置变量。
    Long variable = bigIntegerValue.longValue();

  2. 使用String作为返回类型并转换为Long

    @Query(value = "select distinct(oid) from unit", nativeQuery = true)
    List<String> testMethod();

    然后将值设置为

    Long variable = Long.valueOf(stringValue);

  3. 将数据库列类型更改为整数/数字。

  4. 实体对象获取值。

    Long variable = dpConfigData.getOid();

    哪里dpConfigData是实体对象(DpConfigData.class)

关于postgresql - Spring Data JPA 中的错误 : Spring Data returns List<BigInteger> instead of List<Long>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31011797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com