Java Learning Note-hibernate HQL query

Source: Internet
Author: User

The session is the basis of the persistence layer operation, equivalent to the connection in JDBC, which saves, updates, and finds data through session sessions.
Session is the center of Hibernate operation, object life cycle, transaction management, database access are related to the session
Session created by Sessionfactory is a thread-safe thread-safe that allows multiple threads to access sessionfactory at the same time
and there's no data sharing problem.


Explanation of Session in Hibernate: http://blog.csdn.net/shrek_xu/article/details/740991
Hibernate Note HQL query (a) single attribute, multi-attribute query: http://www.cnblogs.com/zilong882008/archive/2011/11/05/2237123.html

1. HQL's query application:

The Session.createquery () method of Hibernate is to query the object using the HQL statement.

HQL: is a Query object, for example: "From User", where the From is not case-sensitive and the User is case-sensitive because it is an object. is the user class
Returns the Query object.
After executing this statement, Hibernate automatically generates SQL statements for the corresponding database based on the database adapter configured in the configuration file.

Sql:select * FROM Dept; From behind is the table name
Hql:form Dept; The From is followed by a class .

There are two ways to alias a class.
Hql:from Dept D
Hql:from Dept as D

2. Querying a single attribute in a table
Sql:select ename from Dept
Hql:select ename from Dept

You can also set an alias for a property
Hql:select ename as from Dept
As must be added.

3. Multi-Attribute Query

Sql:select Ename,eage from EMP
Hql:select Ename,eage from EMP
Hql:select E.ename,e.eage from Emp E

Note: When querying multiple properties, use the OBEJCT array.

// Third query: For multi-attribute queries Query query3=session.createquery ("Select Ename,eage from Emp");    List<Object[]> list3 =// When querying multiple properties, use the OBEJCT array.  for(object[] message:list3) {    // ) prints an array with the ToString () method of the auxiliary class arrays.      System.out.println (arrays.tostring (message));}  

4. Querying multiple properties by entity class mode

In addition to the above methods, you can also use the Entity class query, to add a constructor with query parameters in the EMP class, the code is as follows.

 Public classEMP {Private intEid; Private inteage; Private floatesal; PrivateString ename; Omit the Get,set method.  PublicEmp () {Super(); } PublicEMP (intEage, String ename) {//what is the property that needs to be queried, and what the constructor's parameters are.     Super();  This. Eage =eage;  This. ename =ename;}

Query code:

query Query=session.createquery ("Select New Emp (eage,ename) from emp e");    
The constructor is called directly after the Select, and the parameters are the properties of the query and the parameters are not garbled. List<Emp> list = query.list (); This is not a practical object array, class type can be for (Emp message:list) { System.out.print ("Name:" +message.getename ( )+" "); System.out.println ("Age:" +message.geteage ());}

====

Example:

Build table

Build Dept tables in database ztest Building an EMP table in the database ztest


CREATE TABLE DEPT (did Integer not NULL PRIMARY KEY, dname VARCHAR (12), daddress VARCHAR (12) , CREATE table EMP (EID INTEGER not NULL PRIMARY KEY, ename VARCHAR (12), eage Integer, esal integer, do integer, insert into DEPT values (1, ' Business unit ', ' address101 ') insert into DEPT values (2, ' Technical department ', ' address201 ') insert into DEPT values (3, ' management Department ', ' address301 ') insert into DEPT values (4, ' Finance department ', ' address401 ') insert into DEPT values (5, ' HR Department ', ' address501 ') insert into EMP values (1, ' Qiao ', 30,10000,1) insert into EMP values (2, ' Yang over ', 25,15020,2) insert into EMP values (3, ' Guo Jing ', 33,23563,1) insert into EMP values (4, ' Botong Tong ', 52,32000,3) insert into EMP values (5, ' Oriental unbeaten ', 43,12000,3) insert into EMP values (6, ' Let Me Go ', 44,16000,4) insert into EMP values (7, ' Ren Ying ', 30,22000,4) insert into EMP values (8, ' Li Mo sorrow ', 42,45000,5) insert into EMP values (9, ' Make Fox Punch ', 35,20000,2) insert into EMP values (10, ' Yue Qun ', 50,42000,2)

To query

 Packagecom.hibernate.hql;Importjava.util.Arrays;Importjava.util.List;ImportOrg.hibernate.Query;Importorg.hibernate.Session;Importorg.hibernate.SessionFactory;Importorg.hibernate.Transaction;Importorg.hibernate.cfg.Configuration; Public classTest { Public Static voidMain (string[] args) {Try{Test1 (); } Catch(Exception e) {e.printstacktrace (); }    }     Public Static voidTest1 ()throwsexception{Configuration config=NewConfiguration (). Configure (); Sessionfactory sessionfactory=config.buildsessionfactory (); Session Session=NULL; Transaction TR=NULL; Try{Session=sessionfactory.opensession (); TR=session.begintransaction (); //First QueryString hql= "from Dept";//defines the string type HQL and writes the HQL statement. Query query=session.createquery (HQL); List<Dept> list =query.list ();  for(Dept dept:list) {System.out.print ("Department Number:" +dept.getdid () + ""); System.out.println ("Department Name:" +dept.getdname ()); }                        //a second queryString hql2 = "from Emp where Eid = 5"; Query Query2=session.createquery (HQL2); List<Emp> List2 =query2.list ();  for(Emp emp:list2) {System.out.print ("Employee Number:" +Emp.geteid ()); System.out.println ("Employee Name:" +emp.getename ()); }                        //Third query: For multi-attribute queriesQuery query3=session.createquery ("Select Ename,eage from Emp"); List<Object[]> List3 =query3.list (); //when querying multiple properties, use the OBEJCT array.              for(object[] message:list3) {//prints an array using the ToString () method of the auxiliary class arrays. System.out.println (arrays.tostring (message));                                                     } tr.commit (); }Catch(Exception e) {tr.rollback (); }finally{            if(session!=NULL) {session.close (); }            if(sessionfactory!=NULL) {sessionfactory.close (); }        }    }}

Java Learning Note-hibernate HQL query

Related Article

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.