"Hibernate step-by-step"--hql Query small Referral

Source: Internet
Author: User
Tags aliases sql using

HQL refers to hibernate query Language, which is hibernate queries the language, has a set of its own query mechanism, its query statements and SQL is very similar, in use can quickly get started. HQL provides essentially all of SQL's query functionality, but there are a lot of places to be aware of when using HQL queries, and this article collates some of the basic grammatical issues that need to be noted in the HQL query process, and you want to avoid these problems when using HQL queries.


First, Hibernate introduction

HQL uses standardized object queries, which are queries in the form of objects, encapsulating query statements as Object operations. Advantages: Good readability, coding habits of composite Java programmers. Cons: not mature enough to support projection or statistical functions.

Example: Querying all users whose user name begins with "J"

Criteria Criteria=session.createcriteria (User.class), Criteria.add (Expression.like ("name", "j%"); List users=criteria.list ();

HQL It is a fully object-oriented query statement, the query function is very powerful, with polymorphism, correlation and other characteristics. It uses an object-oriented approach to generate SQL, substituting classes and attributes for tables and columns of data, supporting polymorphism at the same time, supporting various associations, and reducing the redundancy of SQL.
HQL supports all relational database operations: joins (joins, including Inner/outer/full joins), Cartesian product (Cartesian products), projection (projection), Aggregation (Aggregation,max, AVG) and Group (group), sort (ordering), subquery (subqueries), SQL functions (SQL function calls).

second, the Query method


2.1 CreateQuery
The CreateQuery method is encapsulated in the session and is able to query the query to get the data for the entire table in the database, and it creates a new query interface. The method needs to use the HQL query string as an argument to the method and save the last queried object in the list object. Here's how to use the code:
Package Com.hibernate;import Java.util.iterator;import Java.util.list;import junit.framework.testcase;import Org.hibernate.query;import Org.hibernate.session;public class TestTable extends TestCase {public void Testcreatequery ( {Session session=null;try{//gets Session object Session=hibernateutils.getsession ();//Open transaction session.begintransaction ();// Query gets the entire table query Query=session.createquery ("from User");//Get Form Object list list=query.list ();//define iterators, iterate to get each object for (Iterator Ite=list.iterator (); Ite.hasnext ();) {user user= (user) ite.next (); SYSTEM.OUT.PRINTLN ("ID number is" +user.getid () + "Name:" +user.getname () + "");} Business Submission Session.gettransaction (). commit ();} catch (Exception e) {e.printstacktrace (); Session.gettransaction (). rollback (); Finally{session.close ();}} }


To view the results of the output:


There are a total of three data in the database, so a total of three data is output in the console. Let's look back at the query statement, the CreateQuery method uses the HQL query string, whose content is "from User", which creates a query object that stores the information that is being queried in the list object, and the desired object gets it from the list.

Note: User in the query string is the class name of the object, not the name of the table in the database.

When you use HQL to query content, it is definitely used, it returns a query interface, the queried object can be converted to a list type or a collection of iterate types, the query object can be obtained through an iterator, the collection of two types obtained is not the same. The list type, by default, emits SQL statements each time, and puts the data into the cache, but does not take advantage of the cache; iterate, by default, queries the data from the cache and creates a n+1 problem if no objects exist in the cache (each time the object is loaded into memory using a query statement and then read) , the detailed differences will be discussed in the next article.


2.2 Simple Property Query


When you use the HQL query statement, you can specify the properties of the query table, use the same method as the basic SQL statement, add table fields in the query statement to get the corresponding query field collection, but the field in HQL is the property name of the object, and you need to specify the property name to query for the corresponding field collection.

2.2.1 Query Object student

Create a student class, map the class to the corresponding database table, query the data in the database table, and the student class file inside code as follows:

Package Com.src.hibernate;import Java.util.date;public class Student {public Student () {}//Associated class object private Classes Classes;public Classes getclasses () {return classes;} public void setclasses (Classes Classes) {this.classes = Classes;} Student idprivate int Id;public int getId () {return ID;} public void setId (int id) {this.id = ID;} Student name private string Name;public string GetName () {return name;} public void SetName (String name) {this.name = name;} Creation time Private date Createtime;public date Getcreatetime () {return createtime;} public void Setcreatetime (Date createtime) {this.createtime = Createtime;}}

The corresponding mapping file code is as follows:

<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">



2.2.2 Property Query

A property query is a field column in a SELECT statement that is the property name of the corresponding object, so that you can query for the desired collection of fields based on the provided property columns, and in a simple property query, you can split into a single attribute query and multiple property queries. A single attribute is a single field that adds an object in the Select field, whereas a multi-attribute query adds multiple field columns, and if you want to query all the columns of an object, you can add an alias to the object after select so that you can query all the columns of the object, such as the query code below:

Multiple property queries, return Object@suppresswarnings ({"Unchecked", "rawtypes"}) public void TestQuery2 () {Session session=null;try{ Session=hibernateutils.getsession (); session.begintransaction ();//Query multiple properties, return an array of objects, and query all the column properties of an object by using the object's alias. Use of aliases with sql//if you use Select to query entity objects, you must use alias//HQL not support * query, but support COUNT (*) query list students=session.createquery ("Select S from Student S "). List (); for (Iterator Iter=students.iterator (); Iter.hasnext ();) {Student student= (Student) iter.next (); System.out.println (Student.getname ());} Session.gettransaction (). commit ();} catch (Exception e) {e.printstacktrace (); Session.gettransaction (). rollback (); Finally{hibernateutils.closesession (session);}}


HQL queries do not support * queries, but can be used instead of * queries by using aliases of classes, while HQL supports COUNT (*) queries, which are simple to understand.


2.3 Paged Query

The query object you get can use a paged query to get the specified row data by setting the object's Setfirstresult and Setmaxresults, with the following code:

Try{//gets the Session object Session=hibernateutils.getsession ();//Open transaction session.begintransaction ();//Query get whole table query query= Session.createquery ("from User"),//Paging query//Setting query in fact address Query.setfirstresult (2);//Set query maximum number of bars query.setmaxresults (2);// Gets the Form Object list list=query.list ();//defines iterators, iterating over each object for (Iterator ite=list.iterator (); Ite.hasnext ();) {user user= (user) Ite.next (); SYSTEM.OUT.PRINTLN ("ID number is" +user.getid () + "Name:" +user.getname () + "");} Business Submission Session.gettransaction (). commit ();} catch (Exception e) {e.printstacktrace (); Session.gettransaction (). rollback (); Finally{session.close ();}

Execute the above query statement to get query results such as:



Conclusion

      &NBSP;HQL queries are functionally comparable to SQL queries, but unlike SQL, HQL is a fully object-oriented query language with a polymorphic correlation, which generates SQL using object-oriented methods. Replace tables and table columns with classes and attributes, which are easy to understand when used. This article discusses in detail the basic query content of HQL, and more hql questions will be discussed in the next 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.