Hibernate executes SQL to obtain generic objects

Source: Internet
Author: User

 

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 ();

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.