Hibernate Reading Notes ----- HQL Query

Source: Internet
Author: User

Hibernate provides a powerful query system. You can use Hibernate's HQL query, conditional query, or even native SQL query statements. The powerful query statements configured by Hibernate during HQL query. HQL is consciously designed to be fully object-oriented queries. It can understand concepts such as inheritance, polymorphism, and association.
 
1. HQL Query
The syntax of HQL is similar to that of SQL, but HQL is an object-oriented query statement that operates on classes, instances, and attributes, SQL operation objects are database objects such as data tables and columns.
Because HQL is a fully Object-Oriented Query statement, it supports inheritance, polymorphism, and other features.
HQL Query depends on the Query Class. Each Query instance corresponds to a Query object and its execution is obtained through the createQuery () method of the Session.
To execute an HQL query, follow these steps:
1. Obtain the Hibernate Session Object
2. Compile HQL statements
3. Call the createQuery method of the Session to create a query object.
4. If the HQL statement contains parameters, the setXxx method of the Query is called to assign values to the parameters.
5. Call the list method of the Query object to return the Query result.
Instance:
[Java]
Private void query (){
Session session = HibernateUtil. getSession ();
Transaction tx = session. beginTransaction ();
// Create a Query object using an HQL statement. Execute the setString method to assign values to parameters of the HQL statement.
// Query calls the list method to access all the queried instances.
List list = session. createQuery ("select distinct p from Person p where p. name =: name ")
. SetString ("name", "chenssy"). list ();
 
// Traverse the query results
For (Iterator iterator = list. iterator (); iterator. hasNext ();){
Person p = (Person) iterator. next ();
System. out. println ("id =" + p. getId () + ", age =" + p. getAge ());
}
Session. close ();
}

The above program first writes an HQL statement, and then creates a Query using the createQuery (hql) method of the Session. The Query object uses the setXxx method to assign values to parameters of the HQL statement, and finally calls list () method returns all the results of the query.
Here, the Query object can call the setXxx method multiple times consecutively to assign values to the HQL parameter. This is because the returned value of the setXxx method of Hibernate Query is Query itself. After the program creates a Query, it can directly call the setXxx method multiple times to assign values to parameters of the HQL statement.
The Query object also contains the following two methods:
SetFirstResult (int firstResult): set the number of records returned from the returned result set.
SetMaxResult (int maxResult): sets the number of results returned by this query.
These two methods are used to implement paging Control for HQL queries.
 
Ii. from clause of HQL Query
The simplest query statement in Hibernate is as follows:
[SQL]
From Person
The From keyword is followed by the class name of the persistence class.
In most cases, you need to specify an alias because you may need to reference Person in other parts of the query statement.
[SQL]
From Person as p
Multiple classes can appear in the clause at the same time. The query result is a Cartesian product or a cross-Table connection.
[SQL]
From Person as p, MyEvent as e

Iii. Association and Connection
When the program needs to obtain data from multiple data tables, Hibernate uses Association ing to process connections between underlying data tables. Once we provide correct association ing, when the program uses Hibernate for persistent access, the Hibernate association can be used for connection.
HQL supports two join forms: implicit (implicit) and explicit (explicit ).
The explicit form clause explicitly specifies the join keyword, and implicitly uses the English dot (.) to connect to the correlated entity.
The supported connection types are used for reference in ansi SQL.
Inner join)
Left outer join (left outer join)
Right outer join (right outer join)
Full join (full join, not commonly used)
With explicit join, you can use the with keyword to provide additional join conditions.
[SQL]
From Person as p inner join p. myEvent e with p. id = e. id
From the above, we can see that the with keyword is equivalent to the on keyword in SQL: used to specify the connection condition. In addition, a "fetch" connection allows only one selection statement to initialize the associated object or a set of values with the initialization of their parent object, this method is especially useful when a set is used. For associations and sets, it effectively replaces the Outer Join and delay Declaration (lazy declarations) in the ing file ).
There are two differences between implicit connections and display connections:
1. The underlying layer of the explicit connection will be converted to SQL99 cross join, and the underlying layer of the explicit connection will be converted to SQL99 inner join, left join, right join, and other connections.
2. The results returned by implicit join and explicit join queries are different. The result returned by an implicit join query is a collection of multiple queried objects. The results of explicit join are divided into two types: If the select keyword is omitted in an HQL statement, the returned results are also a set, however, the set element is an array composed of the queried Persistent Object and all associated persistent objects. If the select keyword is not omitted, the returned result is also a set. The elements in the set are arrays composed of persistent objects after the select keyword.
[SQL]
Form Person as p inner join p. myEvent as e with p. id = e. id // ...... 1
 
Select p from Person as p inner join p. myEvent as e with p. id = e. id // ...... 2

The structure returned in ...... 1 is an array composed of the Person object and the MyEvent object. The results returned by... 2 are a set composed of only persons.
For those with set attributes. By default, Hibernate uses a latency loading policy. For example, for persistence class Person, there is a set property myEvent. When a Person instance is loaded, myEvent is not loaded by default. If the session is closed, the Person instance will not be able to access the associated myEvent attribute. To solve this problem, you can configure lazy = "false" in the Hibernate ing file to disable delayed loading. Or use join fetch:
[SQL]
From Person as p join fetch p. myEvent
A fetch connection usually does not need to be specified as an alias, because the associated object should not be used in the where clause (or any other clause. At the same time, the associated objects are not directly returned in the query results, but they can be accessed through their parent objects.
Note the following when using the fetch Keyword:
1. fetch should not be shared with setMaxResults () and setFirstResults,
2. fetch cannot be used together with an independent with Condition
3. If multiple sets are fetch in one query, You can query the returned Cartesian product.
4. full join fetch and right join fetch have no meaning
5. For bag ing, unexpected results may occur when multiple join fetch combinations are performed simultaneously.
 
Iv. select clause
The Select clause is used to Select which objects and attributes are returned to the query result set. Of course, the properties selected by select must be those of the from persistence class.
[SQL]
Select p. name from Person as p
A select query statement can return any type of attribute, including the attribute of a Component whose return type is:
[SQL]
Select p. myEvent. title from Person as p
The select query statement can return multiple objects and/or attributes, which are stored in the Object [] queue:
[SQL]
Select p, e from Person as p inner join p. myEvent as e with p. id = e. id
The Select query statement also supports storing the selected attributes in a List object.
[SQL]
Select new List (p. name, p. age) from Person as p
The Select query statement can also encapsulate the selected attributes into an object.
[SQL]
Select new ClassTest (p. id, p. name, p. age) from Person as p
However, the premise is that ClassTest supports p. id, p. name, p. before the construction of age, if p. the data type of id is int, p. the data type of name is String, p. if the data type of age is int, The ClassTest must have the following constructor:
[Java]
ClassTest (int id, String name, int age)
Select also supports alias for the selected expression Name:
[Html]
Select p. name as personname from Person as p
This method is most useful when used with the clause select new map:
[SQL]
Select new map (p. name as personname) from Person as p
 
V. Aggregate functions
The following aggregation functions are supported:
Avg (...), sum (...), min (...), max (...)
Count (*)
Count (...), count (distinct...), count (all ...)
The Select clause also supports the distinct and all keywords. The effect is the same as that in SQL.
 
6. multi-state Query
Hibernate can understand multi-state queries. After from is followed by the persistence class name, it not only finds all instances of the persistence class, but also finds all instances of all subclasses of the class.
[SQL]
From Person as p
This query statement not only queries all instances of Person, but also queries all attributes of the Child class of Person: Teacher.
Hibernate can specify any Java class or interface in the from clause. The query will return an instance that inherits all persistence classes of the class or an instance that declares all persistence classes of the interface. The following query statement returns all persistent objects:
[Html]
From java. lang. Object o

 
VII. Where clause
The where clause allows you to narrow down the returned instance list. If no alias is specified, you can use the attribute name to directly reference the attribute:
[Html]
From Person where age <40
If an alias is assigned, use the complete attribute name:
[SQL]
From Person as p where p. age <40
The composite attribute expression enhances the where clause function:
[Html]
From person p where p. myEvent. title like "% you are"
The query statement is translated into an SQL query statement containing internal connections.
As long as there is no set attribute, the HQL statement can use the DoT number to implicitly connect multiple data tables:
[Html]
From person p where p. myEvent. event. name like "% hhh ";
The SQL statement must be connected to three tables.
The = operator can be used not only to compare attribute values, but also to compare instances:
[Html]
From Cat cat, Cat rival where cat. mate = rival. mate
[SQL] view plaincopyprint?
From Cat cat, Cat rival where cat. mate = rival. mate
The special attribute (lower-case) id can be used to represent the unique identifier of an object.
[Html]
From Person p where p. id = 1
 
From Person p where p. myEvent. id = 1
The second query is valid. In this case, table join is not required, but an Object-Oriented Query is used completely!
In the case of multi-state persistence, the class keyword is used to access the authentication of an instance. The java class name embedded in the where clause will be used as the identification value of the class.
[SQL]
From Person as p where p. class = Teacher
When executing polymorphism, the instance of Person and all its sub-classes will be selected by default. However, only the instance of the Teacher class will be selected in the preceding HQL statement.
When the where clause operator only supports the basic type or string, the attribute expression in the where clause must end with the basic type or string. do not end with the component type attribute.
 
8. order by clause
The list returned by a query can be sorted by any property in a returned class or component:
[SQL]
From Person as p ordery by p. id
The optional asc or desc keyword indicates the sorting in ascending or descending order.
 
9. group by clause
A query that returns aggregate values can be grouped by any property in a returned class or component:
[SQL]
Select p. id, p. name from Person p group by p. age
You can use the having clause to filter groups.
[Html]
Select p. id, p. name from Person p group by p. age having p. age between 10 and 40
Note: The group by clause and order by clause cannot contain arithmetic expressions. Note that Hibernate does not extend the group entity at present, so you cannot write group by cat unless all cat attributes are not clustered. You must explicitly list all non-clustered attributes.
 
10. subquery
For databases that support subqueries, Hibernate supports using subqueries in queries. A subquery must be enclosed by parentheses (usually the parentheses of SQL clustering functions ). Even correlated subqueries (subqueries that reference aliases in external queries) are allowed.
[Html]
From Person p where p. age> (select avg (p1.age) from Person p1)
Similar to SQL subqueries, if a subquery is a multi-row result set, the multi-row operator should be used. At the same time, HQL subqueries can only appear in the select clause or where clause.
If the select subquery or list contains multiple items, you need to use a tuples constructor in HQL:
[SQL]
From Person as p where (p. name, p. age) in (select s. name, s, age from Student as s)
 
11. name query
HQL queries also support placing the HQL statements used for queries in the configuration file, rather than in program code. This method can greatly improve program decoupling.
Use the <query.../> element in the Hibernate ing file to define the name query. To use the <query.../> element, you must specify a name attribute, which specifies the name of the name query.
[Html]
<Query name = "namedQuery">
<! -- Determine the HQL statement for naming query here -->
From Person as p
</Query>

Session provides a getNamedQuery (String name) method to obtain the specified HQL Query and create a Query object.
[Html]
Public void namedQuery (){
Session session = HibernateUtil. getSession ();
Transaction tx = session. beginTransaction ();
// Execute the name query
List list = session. getNamedQuery ("namedQuery"). list ();
For (Iterator iterator = list. iterator (); iterator. hasNext ();){
Person p = (Person) iterator. next ();
System. out. println (p. getName ());
}
Tx. commit ();
Session. close ();
}


Author: chenssy

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.