Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 999
Oleksandr_DJ Avatar asked Jun 23 '15 19:06

Oleksandr_DJ


2 Answers

This is a issue with Spring data JPA. If in DB the datatype is defined as BigInteger and in JPA query we tries to fetch as Long then it will not give any error , but it set value as BigInteger in Long datatype.

Solutions:

  1. Use BigInteger as return type

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

    then set the variable as below.
    Long variable = bigIntegerValue.longValue();

  2. Use String as return Type and convert to Long

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

    then set the value as

    Long variable = Long.valueOf(stringValue);

  3. Change DB column type to Integer/Number.

  4. Get the Value from Entity Object.

    Long variable = dpConfigData.getOid();

    where dpConfigData is object of Entity(DpConfigData.class)

like image 63
TheSprinter Avatar answered Nov 17 '22 18:11

TheSprinter


BigInt in postgresql maps to BigInteger because its unsigned

I think your best option is to change oid from Long to BigInteger in your JPA object

like image 1
farrellmr Avatar answered Nov 17 '22 19:11

farrellmr