See the following SQL query example:
Private void test ()
{
// Obtain the hibernate Session Object
Session session = hibernateutil. currentsession ();
// Start the transaction
Transaction Tx = session. begintransaction ();
// Write SQL statements
String sqlstring = "select {S. *} from student s where S. name like 'marjun '";
// Create a sqlquery object using an SQL statement
List L = session. createsqlquery (sqlstring)
// Associate the queried records with specific entities
. Addentity ("S", student. Class)
// Return all Record Sets
. List ();
// Traverse the result set
Iterator it = L. iterator ();
While (it. hasnext ())
{
// Because the query result is associated with the student class, the returned student set
Student s = (student) it. Next ();
Set enrolments = S. getenrolments ();
Iterator iter = enrolments. iterator ();
While (ITER. hasnext ())
{
Enrolment E = (enrolment) ITER. Next ();
System. Out. println (E. getcourse (). getname ());
}
}
// Submit the transaction
TX. Commit ();
// Close the session
Hibernateutil. closesession ();
}
The preceding example shows how to associate a query record with an object. In fact, SQL queries also support converting query results into scalar values. You can use the addscalar method to convert them into scalar values, for example:
Double max = (double) Session. createsqlquery ("select max (Cat. weight) as maxweight from cats cat ")
. Addscalar ("maxweight", hibernate. Double );
. Uniqueresult ();