Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've got List<Long> dynamics. And I want to get max result using Collections. This is my code:

List<Long> dynamics=spyPathService.getDynamics();         Long max=((Long)Collections.max(dynamics)).longValue();  

This is my getDynamics:

public List<Long> getDynamics() {          Session session = null;          session = this.sessionFactory.getCurrentSession();         Query query = session                 .createSQLQuery("SELECT COUNT(*) FROM SpyPath WHERE DATE(time)>=DATE_SUB(CURDATE(),INTERVAL 6 DAY) GROUP BY DATE(time) ORDER BY time;");          List<Long> result = query.list();         return result;      } 

Now I'm getting java.math.BigInteger cannot be cast to java.lang.Long. What's wrong?

like image 961
Tony Avatar asked Aug 21 '13 15:08

Tony


People also ask

How do I convert BigInteger to long?

BigInteger. longValue() converts this BigInteger to a long. This conversion is analogous to a narrowing primitive conversion from long to int.

Is bigInt and long the same?

The equivalent of Java long in the context of MySQL variables is BigInt. In Java, the long datatype takes 8 bytes while BigInt also takes the same number of bytes.

Is BigInteger bigger than long?

3. BigInteger Larger Than Long. MAX_VALUE. As we already know, the long data type is a 64-bit two's complement integer.

How do you do math operations with BigInteger in Java?

BigInteger class provides operations analogues to all of Java's primitive integer operators and for all relevant methods from java. lang. Math. It also provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.


2 Answers

Better option is use SQLQuery#addScalar than casting to Long or BigDecimal.

Here is modified query that returns count column as Long

Query query = session              .createSQLQuery("SELECT COUNT(*) as count                              FROM SpyPath                               WHERE DATE(time)>=DATE_SUB(CURDATE(),INTERVAL 6 DAY)                               GROUP BY DATE(time)                               ORDER BY time;")              .addScalar("count", LongType.INSTANCE); 

Then

List<Long> result = query.list(); //No ClassCastException here   

Related link

  • Hibernate javadocs
  • Scalar queries
  • Hibernate.LONG, remember it has been deprecated since Hibernate version 3.6.X
    here is the deprecated document, so you have to use LongType.INSTANCE
  • My previous answer
like image 81
Aniket Kulkarni Avatar answered Sep 29 '22 18:09

Aniket Kulkarni


Your error might be in this line:

List<Long> result = query.list(); 

where query.list() is returning a BigInteger List instead of Long list. Try to change it to.

List<BigInteger> result = query.list(); 
like image 34
Amin Abu-Taleb Avatar answered Sep 29 '22 18:09

Amin Abu-Taleb