What does addScalar do?

This is declaring that you want the result of the query to return objects for individual named columns, rather than entities. For instance

createSQLQuery("SELECT COUNT(*) AS c FROM Users").addScalar("c").uniqueResult()

Will return a single Long. If you specify multiple scalars, the result will come back as an array of Object. Its similar to executeScalar except that it works on named columns, and can return a composite result.


To avoid the overhead of using ResultSetMetadata, or simply to be more explicit in what is returned, one can use addScalar():

session.createSQLQuery("SELECT * FROM CATS")
.addScalar("ID", Hibernate.LONG)
.addScalar("NAME", Hibernate.STRING)
.addScalar("BIRTHDATE", Hibernate.DATE)

This query specified:

the SQL query string
the columns and types to return

This will return Object arrays, but now it will not use ResultSetMetadata but will instead explicitly get the ID, NAME and BIRTHDATE column as respectively a Long, String and a Short from the underlying resultset. This also means that only these three columns will be returned, even though the query is using * and could return more than the three listed columns.

It is possible to leave out the type information for all or some of the scalars.

session.createSQLQuery("SELECT * FROM CATS")
.addScalar("ID", Hibernate.LONG)
.addScalar("NAME")
.addScalar("BIRTHDATE")

This is essentially the same query as before, but now ResultSetMetaData is used to determine the type of NAME and BIRTHDATE, where as the type of ID is explicitly specified.

copied from this.