Search code examples
postgresqlhibernate-mappingspring-data-jpa

Bug in Spring Data JPA: Spring Data returns List<BigInteger> instead of List<Long>


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();
}

And unit test to test menioned DAO:

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

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 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?


Solution

  • 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;
        }
    }