Spring Data返回List <BigInteger>而不是List <Long>

Ole*_*_DJ 15 postgresql hibernate-mapping spring-data-jpa

我有关于spring-data的DAO实现:

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

和单元测试来测试被管理的DAO:

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

运行测试会产生奇怪的结果 - List<Long> testData在运行时由BigInteger实例填充,而不是由Long填充.结果我得到ClassCastException:java.math.BigInteger无法强制转换为java.lang.Long

JPA实现 - Hibernate.作为DB我使用PostgreSQL,unit.oid字段在DB层上有BigInt类型.在获取整个单元的情况下它被映射到Long,但是使用自定义查询作为"select distinct ..."时出现了错误并且它被映射到BigInteger.

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

The*_*ter 7

这是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();

    dpConfigDataEntity(DpConfigData.class)的对象在哪里

  • 在第二种方法中,查询仍然会产生 BigInteger 值。因此采用第一种方法作为解决方案。 (2认同)

Ole*_*_DJ 1

最后我通过在“服务”层上手动映射来解决这个问题。示例(伪代码):

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

然后在服务层我进行手动映射:

public class TestServiceImpl extends TestService {
    pulic List<Object> testMethod(){
        List<Object> rawList = testDataRepository.testMethod();
        List<Object> resultList = new ArrayList(rawList.size());
        for(Object rw:rawList){
            resultList.add(Long.valueOf(String.valueOf(rw)));
        }
        return resultList;
    }
}
Run Code Online (Sandbox Code Playgroud)