加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql – Spring Data返回List而不是List

发布时间:2020-12-13 18:07:54 所属栏目:百科 来源:网络整理
导读:我有关于 spring-data的DAO实现: public interface TestDataRepository extends CrudRepositoryDpConfigData,Long {@Query(value = "select distinct(oid) from unit",nativeQuery = true) ListLong testMethod();} 和单元测试来测试被管理的DAO: @Testpub
我有关于 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无法强制转换为java.lang.Long

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

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

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

解决方案:

>使用BigInteger作为返回类型

@Query(value =“从单元中选择distinct(oid)”,nativeQuery = true)
列表与LT; BigInteger的>测试方法();

然后将变量设置如下.
Long variable = bigIntegerValue.longValue();
>使用String作为返回类型并转换为Long

@Query(value =“从单元中选择distinct(oid)”,nativeQuery = true)
列表与LT;字符串>测试方法();

然后将值设置为

Long variable = Long.valueOf(stringValue);
>将DB列类型更改为Integer / Number.
>从实体对象中获取值.

Long variable = dpConfigData.getOid();

其中dpConfigData是Entity的对象(DpConfigData.class)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读