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