Hibernate several query ways-HQL,QBC,QBE, offline query, compound query, paged query

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/iijse/article/details/6161143

Hql Query method

This is one of my most used and favorite, because it is flexible and intuitive to write, and not much worse than the syntax of the familiar SQL. Conditional query, paged query, connection query, nested query, write up and SQL syntax basically consistent, the only difference is to replace the table name with the class or object. Other, including some query functions (count (), sum (), etc.), query conditions, and so on, all the same as SQL syntax.

Example:
   1:session Session = Sessionfactory.getcurrentsession ();
   2:user User = null;
   3:transaction ts = session.begintransaction ();
   try {
   5:     Query query = session.createquery ("from User as U where name= ' Ijse '");
   6:     user= (user) Query.list (). get (0);
   7:     session.commit ();
   catch (Hibernateexception ex) {
   9:     ts.rollback ();
  Ten:     ex.printstacktrace ();
  11:}
  12:system.out.println (User.getname ());
QBC (query by Criteria) Inquiry method

This approach compares the object-oriented approach, with the emphasis on three objects that describe the condition: restrictions,order,projections. The following three steps are generally required to use QBC queries:

    1. Create a criteria object using the Createcriteria () method of the session instance
    2. Use the tool class restrictions method to set the query criteria for the criteria object, the Order tool class methods to set the sorting method, projections the method of the tool class to be counted and grouped.
    3. Use the list () method of the criteria object to query and return results

Common methods of the restrictions class:

Method name Describe
Restrictions.eq Equals
Restrictions.alleq Use Map,key/valu for multiple equals
Restrictions.gt Greater than
Restrictions.ge Greater than or equal
restrictions.lt Less than
Restrictions.le Less than or equal
Restrictions.between The between of the corresponding SQL
Restrictions.like The like of the corresponding SQL
Restrictions.in The in of the corresponding SQL
Restrictions.and and relationship
Restrictions.or or relationship
Restrictions.sqlrestriction SQL qualified Query

Common methods for order classes:

Method name Describe
Order.asc Ascending
Order.desc Descending

Common methods of projections class

Method name Describe
Projections.avg Averaging
Projections.count Count the number of a property
Projections.countdistinct Count the number of different values for a property
Projections.groupproperty Specifies that a property is a grouped property
Projections.max To find the maximum value
Projections.min To find the minimum value
Projections.projectionlist Create a Projectionlist object
Projections.rowcount Number of record bars in the query result set
Projections.sum To find the total of a property
Example:
   1:session Session = Sessionfactory.getcurrentsession ();
   2:user User = null;
   3:transaction ts = session.begintransaction ();
   try {
   5: Criteria     = Session.createcriteria (User.  Class);
   6:     Criteria.add (Restrictions.eq ("name","Ijse")); 
   7:     user= (user) Criteria.list (). get (0);    
   8:     session.commit ();
   catch (Hibernateexception ex) {
  Ten:     ts.rollback ();
  One:     ex.printstacktrace ();
  12:}
  13:system.out.println (User.getname ());
QBE (query by Example) Query method

Queries a non-empty property of an object as a query condition.

Example:
   1:session Session = Sessionfactory.getcurrentsession ();
   New User ();
   3:user.setname ("Ijse");
   4:transaction ts = session.begintransaction ();
   try {
   6: Criteria     = Session.createcriteria (User.  Class);
   7:     Criteria.add (example.create (user));
   8:     user= (user) Criteria.list (). get (0);    
   9:     session.commit ();
  catch (Hibernateexception ex) {
  One:     ts.rollback ();
  :     ex.printstacktrace ();
  13:}
  14:system.out.println (User.getname ());
Offline query

Offline query is to set up a Detachedcriteria object, specify the condition of the query, and then pass the object in after Session.begintransaction (). Typically, this object can be established in the presentation layer and then passed into the business layer for querying.

Example:
   1:detachedcriteria Detachedcriteria = Detachedcriteria.forclass (User.  Class);
   2:detachedcriteria.add (Restrictions.eq ("name","Ijse"); 
   
   4:session Session = Sessionfactory.getcurrentsession ();
   New User ();
   6:transaction ts = session.begintransaction ();
   try {
   8: Criteria     = Detachedcriteria.getexecutablecriteria (session);
   9:     user= (user) Criteria.list (). get (0);    
  Ten:     session.commit ();
  catch (Hibernateexception ex) {
  :     Ts.rollback ();
  :     ex.printstacktrace ();
  14:}
  15:system.out.println (User.getname ());
Compound query

Compound query is based on the original query and then query, you can call the Criteria object's Createcriteria () method in the criteria object based on the query.

Example:
   1:session Session = Sessionfactory.getcurrentsession ();
   
   3:user ();
   4:transaction ts = session.begintransaction ();
   
   6: {
   7:  
   8:session.createcriteria (a).  Class);
   
  10:criteria2 =criterial1.createcriteria ("User");
  11:  
  12:criteria2.add (Restrictions.eq ("name",new String ("Ijse"));  
  13:  
  
  15:  
  16:session.commit ();
  catch (Hibernateexception ex) {
  18:  
  19:ts.rollback ();
  20:  
  21:ex.printstacktrace ();
  22:}
  23:system.out.println (User.getname ());
Paging Query

A paging query is primarily about specifying two parameters: How many data to take from the first few data. You can set them by calling query or the Setfirstresult () and Setmaxresults () methods of the Criteria object.

Example:
   1:session Session = Sessionfactory.getcurrentsession ();
   2:list userlist = null;
   3:transaction ts = session.begintransaction ();
   try {
   5: Criteria     = Session.createcriteria (User.  Class);
   6:     criteria.setfirstresult (0);  Start with the first data
   7:     Criteria.setmaxresults (ten);  Fetch 10 Records
   8:     userlist = (List) criterial.list ();   
   9:     session.commit ();
  catch (Hibernateexception ex) {
  One:     ts.rollback ();
  :     ex.printstacktrace ();
13:}

Practice (SHZ)
Protected String Perform () throws Exception {
try {
Date today = new Date ();
Date yesterday = Dateutil.adddays (today,-1);
Summerstartdate = Dateutil.getbeginsummerdate (yesterday);
Summerenddate = Dateutil.getendsummerdate (today);
Winterstartdate = Dateutil.getbeginwinterdate (yesterday);
Winterenddate = Dateutil.getendwinterdate (today);

if (Shzstringutil.isnullorempty (perform)) {//is called when the page is entered by default
if (Searchcriteria = = null) {
Searchcriteria = new Forexagentreportcriteria ();
}
Searchcriteria.setstartdate (winterstartdate);
Searchcriteria.setenddate (winterenddate);
}
if (Stringutils.isnotempty (perform) && ShzConstants.PERFORM_SEARCH.equals (perform)) {//is called at the time of query

Final Detachedcriteria Detachedcriteria = Detachedcriteria.forclass (Positiontrans.class);

/***********--------------------Query conditions start----------------**************/
Executetime
Criteriabuilder.buildrange (
Detachedcriteria,
Positiontrans. class,
"Executetime",
Searchcriteria.getstartdate (),
Searchcriteria.getenddate ());

Tradeno
if (Stringutils.isnotempty (Searchcriteria.gettradeno ())) {
Detachedcriteria.add (Restrictions.eq ("Tradeno", Searchcriteria.gettradeno ()));
}
Code
if (! Gwstringutil.isnullorempty (Searchcriteria.getcode ())) {
Detachedcriteria.add (Restrictions.eq ("Code", Searchcriteria.getcode ()));
}

Platform
Searchcriteria.setsortbyfields ("Agentno", "executetime");
Searchcriteria.setsortorders (GWCONSTANTS.ASC, Gwconstants.desc);
/***********--------------------Query condition end----------------**************/
Searchservice.find (Searchcriteria, Detachedcriteria, Super.getlocale (), true);

}
} catch (Exception e) {
Logger.error ("", e);
Throw e;
}
return SUCCESS;
}

Hibernate several query ways-HQL,QBC,QBE, offline query, compound query, paged query

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.