Role:
1. Improve performance
2. Specify which fields to return, for the specified does not return (primarily for select * Query All)
3. You can also specify the specific type of return field
Detailed explanations are as follows:
The most basic SQL query is to get a list of scalars:
Session.createsqlquery ("SELECT * from Person_inf"). List ();
Session.createsqlquery ("Select Id,name,age from Person_inf"). List ();
They all return a list of object arrays, each of which is a field value of the Person_inf table. Hibernate uses ResultSetMetaData to determine the actual order and type of scalar values returned.
However, excessive use of resultsetmetadata in JDBC can degrade program performance. So in order to avoid using resultsetmetadata too much or to specify a more explicit return value type, we can use the Addscalar () method:
Session.createsqlquery ("SELECT * from Person_inf")
. Addscalar ("name", standardbasictypes.string)
. Addscalar ("Age", Standardbasictypes.int)
. List ();
This query specifies the following:
1, SQL query string.
2, the fields and types to return.
It still returns an object array, but instead of using resultsetmetdata at this point, it explicitly removes name and age from the resultset by the string and int types. It also indicates that even if query is queried by using *, it may get more than three fields listed, and will only return these three fields.
You can use Addscalar (String columnalias) If you want to select only the value of a field without explicitly specifying the data type of the field.
public void Scalarquery () {sessions session
= Hibernateutil.getsession ();
Transaction tx = Session.begintransaction ();
String sql = "SELECT * from Person_inf";
List List = Session.createsqlquery (sql).
Addscalar ("person_id", Standardbasictypes.integer).
Addscalar ("name", standardbasictypes.string).
Addscalar ("Age", Standardbasictypes.integer). List ();
for (Iterator iterator = List.iterator (); Iterator.hasnext ();) {
//each collection element is an array, the array element division Person_id,person_name, Person_age three-column value
object[] objects = (object[)) Iterator.next ();
System.out.println ("id=" +objects[0]);
System.out.println ("Name=" +objects[1]);
System.out.println ("age=" +objects[2]);
System.out.println ("----------------------------");
}
Tx.commit ();
Session.close ();
}
It can be seen from above. The Addscalar () method in a scalar query has two functions:
1. Specifies which data columns the query results contain---columns not selected by Addscalar will not be included in the query results.
2, specify the data type of the data column in the query result