问题
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.
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
This is used when your bean has multiple fields with diff types and you want to get these fields in same type from mysql. eg.
public class Example { Long id; String name; }
you can use add scalar as follows
session.createSQLQuery("SELECT * FROM tableName")
.addScalar("id", Hibernate.LONG)
.addScalar("name", Hibernate.STRING);
来源:https://stackoverflow.com/questions/15386571/what-does-addscalar-do