Hibernate retrieval method and the explanation of criteria query

Source: Internet
Author: User

Hibernate framework 5 ways to retrieve

1. Navigation object Graph retrieval Method : Navigating to other objects based on objects that have already been loaded

2.OID Retrieval method : Retrieving Objects by the OID of the object

3.HQL Retrieval method : Using object-oriented HQL Query Language

     4. QBC Retrieval method : using qbc (Query by Criteria) API api encapsulates query statements based on string form, providing a more object-oriented query interface

5. local sql Retrieval method : SQL query statement using local database focus on the criteria query this time , let's first look at it. The criteria query encapsulates the SQL statement by encapsulating the query condition in object-oriented way, also called object Query.
By using the method of object to combine various query conditions , the criteria for generating SQL query statements automatically by Hibernate is created by hibernate Session .
0. the code for the Hibernateutil helper class is as follows

 packageentity;Importorg.hibernate.Session;Importorg.hibernate.SessionFactory;Importorg.hibernate.cfg.Configuration; public classHibernateutil {Private Static FinalThreadLocal sessiontl=NewThreadLocal ();Private StaticConfiguration conf;Private Final Staticsessionfactory sf;Static{    Try{conf=NewConfiguration (). Configure (); SF=conf.buildsessionfactory (); } Catch(Exception Ex) {ex.printstacktrace (); Throw NewExceptionininitializererror (ex); }    } public Staticsession Currentsession () {session session=(Session) Sessiontl.get (); if(session==NULL) {session=sf.opensession ();    Sessiontl.set (session); }    returnsession; } public Static voidCloseSession () {session session=(Session) Sessiontl.get (); Sessiontl.set (NULL);    Session.close (); }}

1. Unconditional Inquiry

    /*      * Unconditional query      */ @Testpublicvoid  critest ()    {=  Hibernateutil.currentsession ();     = session.begintransaction ();     = Session.createcriteria (Dept.class);    List<Dept> list=criteria.list ();      for (Dept dept:list) {        System.out.println (dept.getdeptname ());    }    Tx.commit ();     Hibernateutil.closesession ();    }

2.

 /*   * comparison operation * Conditional query  */  @Test  public  void   critestbyname () {session session  = = session.begintransaction (); List  <Dept> list = Session.createcriteria (dept.class ). Add ( Restrictions. eq     ("deptname", "test department"  for   (Dept dept:list) {System.out.print    ln (dept.getdeptname ());     } tx.commit ();    Hibernateutil.closesession (); }   

3. alias Query

/** Alias Query*/@Test public voidCrinamedtest () {session session=hibernateutil.currentsession (); Transaction TX=session.begintransaction (); criteria Criteria= Session.createcriteria (Emp.class); Criteria. CreateAlias ("dept", "d");//Name the Dept property in EMP as Dlist<emp> list=criteria.add (restrictions.eq ("d.deptname", "test Department")) . List ();  for(Emp emp:list) {System.out.println (emp.getempname ());         } tx.commit ();            Hibernateutil.closesession (); }

4. Range Arithmetic

/** Range Operations * restrictions.in Query*/@Test public voidCriintest () {session session=hibernateutil.currentsession (); Transaction TX=session.begintransaction (); criteria Criteria= Session.createcriteria (Emp.class); List<String> loclist=NewArraylist<>(); Loclist.add ("bj"); List<Emp> List=criteria.add (restrictions.inch("loc", loclist)).        List ();  for(Emp emp:list) {System.out.println (emp.getempname ());         } tx.commit ();            Hibernateutil.closesession (); }

5. Fuzzy Query

/** String pattern matching (fuzzy query)*/@Test public voidCriliketest () {session session=hibernateutil.currentsession (); Transaction TX=session.begintransaction (); criteria Criteria= Session.createcriteria (Emp.class); List<Emp> list= Criteria.add (restrictions. like("loc", "%b%") . List (); //The following function is the same as above, except that the case is ignored//list<emp> list= criteria.add (restrictions.  ilike("loc", "b", matchmode.anywhere)). list ();         for(Emp emp:list) {System.out.println (emp.getempname ());         } tx.commit ();            Hibernateutil.closesession (); }

6. Logical Operation

/** Logical operation and OR not*/@Test public voidCriandtest () {session session=hibernateutil.currentsession (); Transaction TX=session.begintransaction (); criteria Criteria= Session.createcriteria (Emp.class). Add (restrictions. and(restrictions.eq ("empname", "little music"), restrictions.like ("loc", "%b%"))); List<Emp> list =criteria.list ();  for(Emp emp:list) {System.out.println (emp.getempno ());         } tx.commit ();    Hibernateutil.closesession (); }

7. Dynamic Query

/** Dynamic Query*/@Test public voidCridynamictest () {session session=hibernateutil.currentsession (); Transaction TX=session.begintransaction (); EMP EMPCRI=NewEMP (); Empcri.setempname ("little music"); Empcri.setempno (0); criteria Criteria= Session.createcriteria (Emp.class); if(empcri.getempname ()! =NULL) {            //the user fills in the name as the conditionCriteria.add (restrictions.eq ("empname", Empcri.getempname ())); }        if(empcri.getloc ()! =NULL) {criteria.add (restrictions.gt ("empNo", Empcri.getempno ())); } List<Emp> list =criteria.list ();  for(Emp emp:list) {System.out.println (emp.getempno ());         } tx.commit ();    Hibernateutil.closesession (); }

8. Sorting

/** Sort*/@Test public voidCriordertest () {session session=hibernateutil.currentsession (); Transaction TX=session.begintransaction (); criteria Criteria= Session.createcriteria (Emp.class); List<Emp> list = Criteria.AddOrder(ORDER.ASC("empNo") . List ();  for(Emp emp:list) {System.out.println (emp.getempname ());         } tx.commit ();    Hibernateutil.closesession (); }

9. Paging

/** Paging*/@Test public voidCripagetest () {session session=hibernateutil.currentsession (); Transaction TX=session.begintransaction (); criteria Criteria= Session.createcriteria (Emp.class); intpageindex=2;//Current page number        intpagesize=2;//the amount of data displayed per pageCriteria.Setfirstresult((pageIndex-1) *pageSize); Criteria. Setmaxresults        (pageSize); List<Emp> list =criteria.list ();  for(Emp emp:list) {System.out.println (emp.getempname ());         } tx.commit ();            Hibernateutil.closesession (); }

Detachedcriteria Query

/** Detachedcriteria Query*/@Test public voidDetachedcritest () {session session=hibernateutil.currentsession (); Detachedcriteria DC=detachedcriteria.forclass (Emp.class, "e"); Dc.createalias ("e.dept", "d"). Add (restrictions.eq ("d.deptname", "test department")); List<Emp> list=Dc.getexecutablecriteria (session). List ();  for(Emp emp:list) {System.out.println (emp.getempname ());             } hibernateutil.closesession (); }

Hibernate retrieval method and the explanation of criteria 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.