Hibernate (ix) HQL query

Source: Internet
Author: User

First, Hibernate provides the Query method
    • OID Query method: Primary key query. An object that loads the specified OID through the get () or load () method results in a
    • Hql Query method: query interface using the HQL language
    • QBC Query method: Through the criteria and other interfaces and classes are query
    • Local SQL Query method: Query using native SQL language
    • Object Navigation Query method: Navigate to its associated object through an already loaded object

Among them, HQL and QBC are the professional query methods provided by Hibernater.

Hql Query method is the official recommended standard Query method

second, HQL inquiry brief

HQL: Hibernate Query Language

This language looks much like SQL. But instead of being fooled by the similarity in grammatical structures, hql is very conscious of being designed as a fully object-oriented query that can understand concepts such as inheritance, polymorphism, and correlation.

For example:

                //1. Get SessionSession session=hibernatesessionfactory.getsession (); //2. Create a query statement here student is a persisted class, class nameString hql= "from Student"; //String hql= "from Student where Sname= ' Zhang San '"; //3. Create a Query objectQuery query=session.createquery (HQL); //4. Execute the query to return the result to the list collectionList<student> list=query.list (); //5. Output Results         for(Student stu:list) {System.out.println (Stu.getsname ()+stu.getsex ()); }                    
Three, the simplest query

Search All information

From Student    // Use persistent class name directly from com.pb.entity.Student  // use full path

Generally we do not need to use the fully qualified name of the class, because auto-import(Auto-Introduction) is the default condition.

You can also specify an alias for the class name

From Student as S     // use the AS keyword to specify the alias of the class from Student s  // omit the AS keyword to specify the alias of the class 
iv. WHERE clause

You can also support the WHERE clause

From Student where sid=201503011 fromStudent  s where s.sid=201503011
4.1. You can use various operators in where

For example:

From Student where sex= ' man ' and sid<11070200// Query Student gender for male, student number less than 11070200 students  11070100 and 11070200// Inquiry student number between 11070100 and 11070200 students from Student where  '% Fly '; // Check student's name last word for flying all students  ' _ik* '; // Check the student's name, the first word is any, the 2nd is I, the 3rd is K, the student of any length behind

Where "-" matches a single character

"%" matches characters of any length

"_" Can not be used to match Chinese characters, "%" can be used to match Chinese characters

V. Return of results

How to Query

5.1. List () method
//1. Get SessionSession session=hibernatesessionfactory.getsession (); //2. Create a query statement here student is a persisted class, class nameString hql= "from Student"; //String hql= "from Student where sid=201503011"; //3. Create a Query objectQuery query=session.createquery (HQL); //4. Execute the query to return the result to the list collectionList<student> list=query.list (); //5. Output Results         for(Student stu:list) {System.out.println (Stu.getsname ()+stu.getsex ()); }
5.2. Iterate () method
//1. Get SessionSession session=hibernatesessionfactory.getsession (); //2. Create a query statement here student is a persisted class, class nameString hql= "from Student"; //String hql= "from Student where sid=201503011"; //3. Create a Query objectQuery query=session.createquery (HQL); //4. The execution query returns the result as iteratorIterator<student> iterator=query.iterate (); //5. Output Results         while(Iterator.hasnext ()) {Student Stu=Iterator.next (); System.out.println (Stu.getsname ()+stu.getsex ()); }        
5.3. Uniqueresult () method

The returned result is an object that is typically used to query based on the primary key

//1. Get SessionSession session=hibernatesessionfactory.getsession (); //2. Create a query statement here student is a persisted class, class name//String hql= "from Student";String hql= "from Student where sid=201503011"; //3. Create a Query objectQuery query=session.createquery (HQL); //4. Execute the query to return the result to type object,Student student=(Student) Query.uniqueresult (); //5. Output ResultsSystem.out.println (Student.getsname () +student.getsex ());
5.4. List () and iterate () method differences

The query mechanism of both are different

When using list (), you only need to query one time to complete all persisted classes, all fields of the query

When using iterate (), the first query is all the records of the primary key ID, and then go to the system cache query the corresponding records, if there is a record of this ID, will not be database query, if there is no database query, how many records will be queried 1+n times.

Six, attribute query (projection query) 6.1, directly specify the property query

Returns the result as an object array, the length of the array is the number of attributes

 Public Static voidFindbyproperty () {//1. Get SessionSession session=hibernatesessionfactory.getsession (); //2. Create a query statement here student is a persisted class, class name//String hql= "from Student";String hql= "Select Sid,sname,sex from Student"; //3. Create a Query objectQuery query=session.createquery (HQL); //4. Execute the query to return the result to type object,List list=query.list (); //5. Output Results         for(Object object:list) {//an array of object objects that result in query property dataObject [] obj=(object[]) Object; System.out.println (obj[0]+ "\ t" +obj[1]+ "\ T" +obj[2]); }            }
6.2, using the Construction method query

The premise is that this constructor should be used in the persistence class

Returns a collection of objects that result as persisted classes

 Public Static voidfindbycons () {//1. Get SessionSession session=hibernatesessionfactory.getsession (); //2. Create a query statement here student is a persisted class, class name//String hql= "from Student";String hql= "Select New Student (sid,sname,sex) from Student"; //3. Create a Query objectQuery query=session.createquery (HQL); //4. Execute the query to return the result to type object,List<student> list=query.list (); //5. Output Results         for(Student stu:list) {System.out.println (Stu.getsname ()+ "\ T" +stu.getsex ()); }            }

This is more direct, clear understanding, must have the corresponding construction method

VII. entity update and deletion 7.1, update
    Session session =new  Configuration (). Configure (). Buildsessionfactory (). Opensession ();        Student stu= (Student) session.get (Student.  Class, 201509009);                Course cou= (Course) session.get (Course.  Class, 2222);                Transaction Tran=session.begintransaction ();        Stu.getcourses (). Add (cou);        Session.update (Stu);        Tran.commit ();        Session.close ();
View Code7.2. Delete
Session session =new  Configuration (). Configure (). Buildsessionfactory (). Opensession ();        Student stu= (Student) session.get (Student.  Class, 201509009);                Course cou= (Course) session.get (Course.  Class, 2222);                Transaction Tran=session.begintransaction ();        Stu.getcourses (). Remove (cou);        Session.update (Stu);        Tran.commit ();        Session.close ();
View CodeEight, parameter binding 8.1 placeholder,

Use the same as in JDBC? to occupy a position

8.2. Named parameters

Nine, sort

X. Statistical functions

 public  static  void   Findcount () {Session session  =new<        /span> /*  string hql= "from EMP";        Query query=session.createquery (HQL);        List list=query.list (); int count=list.size ();  */         String hql  = "SELECT count (*) from EMP"  =session.createquery (HQL);        Long Count  = (Long) Query.uniqueresult ();            SYSTEM.OUT.PRINTLN ( Total Employee table records: "+count); }    
View Code

Hibernate (ix) 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.