Hibernate's HQL Query

Source: Internet
Author: User

I. Introduction of HQL

HQL (Hibernate query Language) is an object-oriented query language that relies on the query class, each of which corresponds to a querying object. The query steps are as follows:

1) Get Hibernate Session Object

2) Writing HQL statements

3) Call the session's CreateQuery () method to create a query condition with the HQL statement as the argument

4) If the HQL statement contains parameters, call query's Setxxx () method to assign a value to the parameter

5) Call the list () or the Uniqueresult () method of the query object to return the results of the search (persisted entity set)

Second, HQL query

1. FROM clause

String hql = "from Hqlteacher"= session.createquery (HQL); List<HQLTeacher> list =for(Hqlteacher t:list) System.out.println (T.getname ());

Multiple persisted classes can also appear after the From, resulting in a Cartesian product or cross-table connection

A, Cartesian product

String hql = "from Hqlteacher,hqlstudent";             = Session.createquery (hql);             = query.list ();             int i = 0;              for (Object t:list) {//At this time t is an array                of length 2 = (object[]                ) t; = (Hqlteacher) ob[0];                 = (hqlstudent) ob[1];                System.out.println (++i + ":" + ht.getname () + "|" + hs.getname ());//The result bar number is the product of teacher and student bars            }

B, Connection

 String hql = "from Hqlteacher as t,hqlstudent as s where t.id = S.hqlteacher" ;// Hqlteacher is associated with teacher in student, query query  = SESSION.C if there is no associated mapping to fill in the name of the corresponding associated key            Reatequery (HQL);            List List  = Query.list ();             int  i = 0;  for   (Object t:list) {object[] ob                 = (object[]) t;                Hqlteacher HT  = (hqlteacher) ob[0];                Hqlstudent HS  = (hqlstudent) ob[1];            System.out.println ( ++i + ":" + ht.getname () + "|" + Hs.getname ()); }

When you use a cross-table connection in real-world development, you typically choose to use either implicit or explicit joins, rather than following the from immediately after multiple persistent session classes.

2, association and connection ( precondition Persistence class has mapped association inside )

HQL supports two kinds of associative connections: implicit and explicit

A, implicit (do not use the Join keyword, use English. To implicitly connect an associated entity)

        String hql = "from hqlstudent as s where S.hqlteacher.name =: Name";             = Session.createquery (HQL);            Query.setstring ("name", "Teacher 1");//At this time only the name of teacher 1 is obtained student column            list<HQLStudent> list = query.list ();              for (hqlstudent s:list) {                + "|" + s.gethqlteacher (). GetName ());            }

The code above uses the placeholder (: name), HQL provides two placeholder methods: English question mark + index form (? N) and preceded by the name with a colon (: parameter name)

B, an explicit

        String hql = "from hqlstudent as s inner join S.hqlteacher";//Explicit Association is not the other party's persisted class, but the other side persisted class in this class the association entity, and eliminates the association condition in the SQL statement (on the following            content)= session.createquery (hql            ); = query.list ();//is different from implicit association, when the result set is stored in a query persisted object and the associated persisted object is composed of an object            array of int i = 0;              for (Object t:list) {                = (object[]) t;                 = (hqlstudent) ob[0];                 = (Hqlteacher) ob[1];                System.out.println (++i + ":" + ht.getname () + "|" + hs.getname ());            }

As with SQL Association, there are four explicit associations, inner join (inner join), left join (Zuo connection), right join (starboard Lianjie), full join (outer join)

3. SELECT clause

Select for selecting a specified attribute or directly selecting an entity

A, only one after the Select

        String hql = "Select S.name from Hqlstudent as S";             = Session.createquery (HQL);            List<String> list = query.list ();//At this time the result set is            the set of attributes corresponding to int i = 0;              for (String s:list) {                System.out.println (++i + ":" + s);            }

b, select after a number of

        String hql = "Select S.name,s.hqlteacher.name from Hqlstudent as S";             = Session.createquery (hql);             = query.list ();//The element of the result set at this time is an            array of choices consisting of an int i = 0;              for (Object ob:list) {                = (object[]) ob;                System.out.println (++i + ":" + ob1[0] + "|" + ob1[1]);            }

C, select also supports storing selected attributes in a list object

        String hql = "Select New List (S.name,s.hqlteacher.name) from hqlstudent as S";//via New list ()             = session . CreateQuery (HQL);            List<List> list = query.list ();             int i = 0;              for (List ob:list) {                System.out.println (++i + ":" + ob.get (0) + "|" + ob.get (1));            }

D, select also supports encapsulating selected attributes directly into an object

        String hql = "Select New Entity.hql.StudentTeacher (S.name as studentname,s.hqlteacher.name as TeacherName) from Hqlstuden T as S ";             = Session.createquery (HQL);            List<StudentTeacher> list = query.list ();             int i = 0;              for (Studentteacher st:list) {                System.out.println (++i + ":" + st.getstudentname () + "|" + St.gette Achername ());            }

It is important to note that the Studentteacher class needs to be written in full with the package name, with attributes that have the same name as the selection attribute, and with the same construction method as the number of selected attributes, creating the object class as follows

 Packageentity.hql;// Package name  Public classStudentteacher {
corresponding attributes PrivateString Studentname; PrivateString TeacherName; PublicStudentteacher (String studentname, String teachername) {// constructor method This. Studentname =Studentname; This. TeacherName =TeacherName; } PublicString Getstudentname () {returnStudentname; } Public voidsetstudentname (String studentname) { This. Studentname =Studentname; } PublicString Getteachername () {returnTeacherName; } Public voidsetteachername (String teachername) { This. TeacherName =TeacherName; }}

4. Aggregation function

        String hql = "SELECT count (*) from hqlstudent as S";             = Session.createquery (HQL);            System.out.println (Query.uniqueresult ());

The aggregation functions supported by HQL are identical to SQL, with AVG, COUNT, max, Min, sum

In addition, like SQL, HQL also supports the WHERE clause, expression, order by, group BY, and subquery, and the implementation is basically the same as SQL, which is no longer described here.

The attachment gives the persistence class and Hibernate startup code used in the test
@Entity @table (name= "Hql_student") Public classhqlstudent {@Id @GeneratedValuePrivateLong ID; PrivateString name; @ManyToOne (targetentity= Hqlteacher.class) @JoinColumn (name= "teacher_id", referencedcolumnname = "id")    PrivateHqlteacher Hqlteacher;  PublicLong getId () {returnID; }     Public voidsetId (Long id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicHqlteacher Gethqlteacher () {returnHqlteacher; }     Public voidSethqlteacher (Hqlteacher hqlteacher) { This. Hqlteacher =Hqlteacher; }}
@Entity @table (name= "Hql_teacher") Public classhqlteacher {@Id @GeneratedValuePrivateLong ID; PrivateString name; @OneToMany (targetentity= Hqlstudent.class, Mappedby = "Hqlteacher")    PrivateSetNewHashset();  PublicLong getId () {returnID; }     Public voidsetId (Long id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicSetgethqlstudents () {returnhqlstudents; }     Public voidSethqlstudents (sethqlstudents) {         This. hqlstudents =hqlstudents; }}
 Public classHqltestcontroller { Public Static voidMain (string[] args) {Configuration CF=NewConfiguration (). Configure (); Sessionfactory SF=cf.buildsessionfactory (); Session Session=sf.opensession (); Transaction TS=session.begintransaction (); Try{String hql= "SELECT count (*) from hqlstudent as S"; Query Query=session.createquery (HQL);            System.out.println (Query.uniqueresult ());        Ts.commit (); } finally{session.close ();        Sf.close (); }    }}

Hibernate's HQL 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.