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

java, long-integer, sql

Solution

Use `BigInteger#longValue()` method, instead of casting it to `Long`:

return firstResult.get(0).longValue();

Seems like `firstResult.get(0)` returns an `Object`. One option is to typecast to `BigInteger`:

return ((BigInteger)firstResult.get(0)).longValue();

But don't do this. Instead use the way provided by Nambari in comments. I'm no user of Hibernate, so I can't provide Hibernate specific solution.

Problem

I want to return number of rows using native sql. But console says me `java.math.BigInteger cannot be cast to java.lang.Long`. What's wrong? This is my method: ``` public Long getNumRows(Integer id){ Session session = null; session = this.sessionFactory.getCurrentSession(); Query query = session .createSQLQuery("SELECT COUNT(*) FROM controllnews WHERE news_id=" + id + ";"); List firstResult = query.list(); return (Long) firstResult.get(0); } ```

Original source