0

I have a List ids populated by database query (Hibernate). The database is PSQL. The ids column is bigint type. Now the ids list is populated without any exception like this

List<Long> ids = getIds();//getIds returns List<Long>

but when I try to loop through the items on the ids list by

 for (Long id : ids)

I get the exception

java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long

The value is 206131954. I don't know why it can add the value to the list, but later there is the error when trying to go through the list.

public List<Long> getIds() {
    List<Long> externalIds = new ArrayList<Long>();
    List<Person> persons = repository.getPeople();
    for (Person person : persons) {
        List<Long> ids = repository.getIdentifications(person);
        if (ids.size() > 0) {
            externalIds.addAll(ids);
        }
    }
    return externalIds;
}

public List<Long> getIdentifications() {
    String q = "select person_id from relevantpeople";
    Query query = entityManager.createNativeQuery(q);
    return (List<Long>) query.getResultList();
}
krltos
  • 313
  • 4
  • 20

1 Answers1

0

Use List<BigInteger> instead of List<Long>

BigInteger is capable of holding bigger integer numbers than Long.

BigInteger holds (2^32)^Integer.MAX_VALUE;

Long holds (2^63)-1;

GuilhermeFGL
  • 2,891
  • 3
  • 15
  • 33
  • But the value on the list (there is only one item in this case) is 206131954 so it easily fits in the range of Long. I don't wanna simply change that to BigInteger only because of the range difference. My ids won't be for sure higher than Long can hold. – krltos Nov 27 '17 at 12:53
  • 1
    Does not matter the value of the current cursor of the query. What matters is the type of the column of your table. If the column you are trying to read in the table `Person` is defined as `BigInt`, so this is the type you have to handle. – GuilhermeFGL Nov 27 '17 at 12:58