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:
String query ="select count(*) from tablename";
Number count = (Number) sessionFactory.getCurrentSession().createSQLQuery(query).uniqueResult();
Long value = count.longValue();
I tried this it works well
I faced same problem, I used Hibernate Scalar queries as suggested in the comment of @Rohit Jain's answer. Thanks @nambari for comment.
Coming to the problem we have,
Query query = session
.createSQLQuery("SELECT COUNT(*) FROM controllnews WHERE news_id="
+ id + ";");
These will return a List of Object arrays (Object[]) with scalar values for each column in the controllnews
table. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values.
To avoid the overhead of using ResultSetMetadata, or simply to be more explicit in what is returned, one can use addScalar():
Query query = session
.createSQLQuery("SELECT COUNT(*) as count FROM controllnews WHERE news_id="
+ id + ";").addScalar("count", LongType.INSTANCE);
This will return Object arrays, but now it will not use ResultSetMetadata but will instead explicitly get the count
column as Long
from the underlying resultset.
How the java.sql.Types
returned from ResultSetMetaData is mapped to Hibernate types is controlled by the Dialect. If a specific type is not mapped, or does not result in the expected type, it is possible to customize it via calls to registerHibernateType
in the Dialect.
You can use Query#setParameter method to avoid any mistakes in query as
Query query = session
.createSQLQuery("SELECT COUNT(*) as count FROM controllnews WHERE news_id= :id")
.addScalar("count", LongType.INSTANCE).setParameter("id",id);
One confusion when you refer Scalar queries docs 4.0, addScalar
method has second parameter 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
Related link
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.