The JavaDoc says:
SQLQuery org.hibernate.SQLQuery.addScalar(String columnAlias, Type type) Declare a scalar query result
I know what executeScalar
is in C#, but this scalar and C# scalar seem to be absolutely different.
Hibernate SQL Query addScalar Hibernate uses ResultSetMetadata to deduce the type of the columns returned by the query, from performance point of view we can use addScalar() method to define the data type of the column.
addScalar is an information of returnType for a given key in SQL query. Example: Query a = new SqlQuery("Select username as un from users where ..."); a. addScalar("un", String); If you query for result, the result will be String or other types if you specify.
Scalar Queries The most basic SQL query is to get a list of scalars (values) from one or more tables. Following is the syntax for using native SQL for scalar values − String sql = "SELECT first_name, salary FROM EMPLOYEE"; SQLQuery query = session.
Hibernate Query Language (HQL) supports various aggregate functions – min(), max(), sum(), avg(), and count() in the SELECT statement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With