Spring Data JPA中的错误:Spring Data返回List< BigInteger>而不是List< Long> [英] Bug in Spring Data JPA: Spring Data returns List<BigInteger> instead of List<Long>
问题描述
我在spring-data上实现了DAO:
I have DAO implementation over spring-data:
public interface TestDataRepository extends CrudRepository<DpConfigData, Long> {
@Query(value = "select distinct(oid) from unit", nativeQuery = true)
List<Long> testMethod();
}
并进行单元测试以测试提及的DAO:
And unit test to test menioned DAO:
@Test
public void test(){
List<Long> testData = dpConfigDataEntityDataRepository.testMethod();
for (Long oid:testData){
System.out.print(oid);
}
}
运行测试给出奇怪的结果-列表< Long>运行时中的testData
由BigInteger实例而非Long填充。结果我得到 ClassCastException:java.math.BigInteger无法转换为java.lang.Long
Running test give strange result - List<Long> testData
in runtime is populated by BigInteger instances, not by Long. As result I get ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
JPA实现-休眠。
当数据库使用PostgreSQL时, unit.oid
字段在数据库层上具有BigInt类型。
在获取整个单位的情况下将其映射为Long,但是在将自定义查询作为选择不同的……时出现了问题,因此将其映射为BigInteger。
JPA implementation - Hibernate.
As DB I use PostgreSQL, unit.oid
field has BigInt type on DB layer.
It is mapped to Long in case of fetching whole unit, but with custom query as "select distinct ..." something went wrong and it is mapped to BigInteger.
所以,我的问题是:这种奇怪行为的原因是什么?
如何以一种优雅的方式解决/解决它?
So, my question: what is the cause of such strange behaviour? How to solve/workaround it in elegant way?
推荐答案
最后,我通过在服务层。
示例(伪代码):
Finally I worked around this problem by manual mapping on "service" layer. Example(pseudo code):
public interface TestDataRepository extends CrudRepository<DpConfigData, Long> {
@Query(value = "select distinct(oid) from unit", nativeQuery = true)
List<Object> testMethod();
}
}
然后在服务层中进行手动映射:
then in Service Layer I do manual mapping:
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;
}
}
这篇关于Spring Data JPA中的错误:Spring Data返回List< BigInteger>而不是List< Long>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!