HQL Query Language Summary of hibernate
HQL is short for Hibernate Query Language. HQL syntax is similar to SQL syntax, but HQL is an Object-Oriented Query Language. Therefore,SQL operation objects are data objects such as data tables and columns., AndHQL operation objects include classes, instances, and attributes.
HQL is a fully Object-Oriented Query Language. Therefore, it supports inheritance, polymorphism, and other features.
HQL query steps:
1. Obtain the Hibernate Session object.
2. Compile an HQL statement.
3. Use HQL as the parameter to call createQuery of the Session to create a Query object (if the HQL statement has a parameter, assign a value to the set Method of the Query ).
4. Call the list and other methods of the Query object to return to the instance.
For example:
LearningDAO learningDao = new LearningDAO (); Configuration cfg = new Configuration (). configure (); SessionFactory sessionFactory = learningDao. getSessionFactory (); Session session = sessionFactory. openSession (); // obtain the session Object Transaction tran = session. beginTransaction (); Query query = session. createQuery (from Learning); // HQL statement, create the Query object List = query. list (); for (int I = 0; I
Common syntax of HQL statements:
HQL statements are case-insensitive. That is to say, the keywords and functions of HQL statements are case insensitive. However, the package name, class name, Instance name, and attribute name used in HQL statements are case sensitive.
1. from clause of HQL Query
The from clause is the simplest HQL statement and the most basic HQL statement. The from keyword is followed by the class name of the persistence class,
For example:
From City; indicates that all instances are selected from the City persistence class.
In most cases, we recommend that you create an alias for each instance of the City.
For example:
From City as c
In the preceding HQL statement, the instance alias of the City persistence class is c. Since c is the Instance name, Java Naming rules should also be followed: the first letter of the first word is lowercase, the first letter of each word is capitalized.
When naming aliases,The as keyword is optional.But it is recommended to keep it for readability.
For example:
From City c
Multiple persistence classes can appear at the same time after the from statement. At this time, a Cartesian Product or cross-table join will be generated.
2. select clause for HQL query:
The select clause selects the objects and attributes returned to the query result set. The select clause is used to determine the selected attributes. Of course, the attributes selected by the select clause must be the attributes contained in the persistence class after the from clause.
Select can select any attribute,You can select not only the direct attributes of the persistence class, but also the attributes contained in the component attributes,
For example:
select p.name.firstName from Person as p
Select also supports
The selected attribute is saved to a List object.For example:
select new list(p.name , p.address) from Person as p
You can even encapsulate the selected Attribute into an object. For example:
select new ClassTest(p.name , p.address) from Person as p
The premise is that ClassTest supports p. name and p. address constructor, if p. the data type of name is String, p. if the data type of address is String, the ClassTest must have the following constructor:
ClassTest (String s1, String s2)
Select also supports
Alias for the selected expressionFor example:
select p.name as personName from Person as p
This usage is more common when combined with new map. For example:
select new map(p.name as personName) from Person as p
In this case, the Map structure is selected, with the personName as the key, and the actually selected value as the value.
3. HQL query Aggregate functions
HQL queries can even return the computing results of Aggregate functions acting on attributes:
select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat)from Cat cat
● Avg: calculate the average attribute value.
● Count: count the number of selected objects.
● Max: maximum value of the statistical Attribute Value
● Min: calculates the minimum value of the attribute value.
● Sum: calculates the sum of attribute values.
4. multi-state Query
HQL statements can be designed to understand multi-state queries, with the persistence class name followed by from,Not only can all instances of the persistence class be queried, but all instances of the subclass of the class are also queried.
The following query statement:
from Person as p
This query statement
Not only all instances of Person are queried, but also child classes of Person are queried,For example, if all the instances of Teacher have completed the correct inheritance ing between Person and Teacher.
5. where clause for HQL Query
The where clause allows you to narrow down the returned instance list. If no alias is specified, you canUse the property name to directly reference the property:
From Cat where name = 'fritz'
If an alias is assigned, use the complete attribute name:
From Cat as cat where cat. name = 'fritz'
Returns an instance of the Cat class named (with the property name equal to) 'fritz.
The composite attribute expression enhances the where clause function, for example, the following HQL statement:
From Cat cat where cat. mate. name like kit %
This query will be translated into an SQL query containing internal connections. The translated SQL statement is as follows:
select * from cat_table as table1 cat_table as table2 where table1.mate =table2.id and table1.name like kit%
Let's look at the following HQL query statement:
from Foo foo where foo.bar.baz.customer.address.city likeguangzhou%
Translated into an SQL query statement, it will be a query with four table connections.
The = operator can be used not only to compare attribute values, but also to compare instances:
from Cat cat, Cat rival where cat.mate = rival.mateselect cat, matefrom Cat cat, Cat matewhere cat.mate = mate
Expression in the where clause:
● Mathematical operators + ,-,*,/? .
● Binary comparison operators =, >=, <=, <>, and ,! =, Like, etc.
● Logical operators such as and, or, and not.
● In, not in, between, is null, is not null, is empty, is not empty, member of and not member.
● Simple case, case... when... then... else... end, case, case when... then... else... end.
● String connector value1 | value2 or use the string connection function concat (value1, value2 ).
● Time operation functions: current_date (), current_time (), current_timestamp (), second (), minute (), hour (), day (), month (), year ().
● HQL also supports functions or operations supported by EJB-QL 3.0 substring (), trim (), lower (), upper (), length (), locate (), abs (), sqrt (), bit_length (), coalesce (), and nullif.
● It also supports database type conversion functions, such as cast (... as ...), the second parameter is the type name of Hibernate, or extract (... from ...), the premise is that the underlying database supports ANSI cast ()? And extract ().
● If the underlying database supports the following single-row functions: sign (), trunc (), rtrim (), and sin (). The HQL statement is also fully supported.
● Can I use HQL statements? As a parameter placeholder, which is consistent with the parameter placeholder of JDBC. You can also use the placeholder symbol of the named parameter by adding a colon Before the parameter name, such as start_date and: x1.
● Of course, you can also use SQL CONSTANTS IN THE where clause, such as 'foo', 69, and '2017-01-01 10: 00: 100.
● You can also use constants of the Java public static final type in HQL statements, such as eg. Color. TABBY.
In addition, the where clause also supports the following special keyword usage.
● In and between... and can be used as follows:
from DomesticCat cat where cat.name between 'A' and 'B'from DomesticCat cat where cat.name in ( 'Foo','Bar','Baz')
● Of course, the use of not in and not between... and is also supported, for example:
from DomesticCat cat where cat.name not between 'A' and 'B'from DomesticCat cat where cat.name not in ( 'Foo','Bar','Baz' )
● Clauses is null and is not null can be used to test null values. For example:
from DomesticCat cat where cat.name is null;from Person as p where p.address is not null;
If the following declaration is made in the Hibernate configuration file:
True 1, false 0
The preceding statement indicates that when HQL converts an SQL statement, the true and false keywords are replaced by characters 1 and 0. Then you can use a Boolean expression in the expression, for example:
From Cat cat where cat. alive = true
● The size keyword is used to return the size of a set, for example:
from Cat cat where cat.kittens.size > 0from Cat cat where size(cat.kittens) > 0
● For ordered sets, the minindex and maxindex functions can also be used to represent the smallest and largest index ordinal numbers. Similarly, the minelement and maxelement functions can be used to represent the smallest and largest elements in the set. For example:
from Calendar cal where maxelement(cal.holidays) > current datefrom Order order where maxindex(order.items) > 100from Order order where minelement(order.items) > 10000
● You can use SQL functions any, some, all, exists, or in to operate elements in the set, for example:
// Select mother from Cat as mother, Cat as kitwhere kit in elements (foo. kittens) // The name attribute of p is equal to the name attribute of an element in the Set select p from NameList list, Person pwhere p. name = some elements (list. names) // operation set element from Cat cat where exists elements (cat. kittens) from Player p where 3> all elements (p. scores) from Show show where 'fizard 'in indices (show. acts)
Note that these structure variables such as size, elements, indices, minindex, maxindex, minelement, and maxelement can only be used in the where clause.
● In the where clause, elements (arrays, lists, maps) of an ordered set can be accessed through the [] operator. For example:
// Items is an ordered set attribute. items [0] indicates the first element from Order order where order. items [0]. id = 1234 // holidays is a map set attribute. holidays [national day] represents one of the elements select person from Person person, Calendar calendarwhere calendar. holidays ['National Day'] = person. birthDayand person. nationality. calendar = calendar // select item from Item item, Order orderwhere order. items [order. deliveredItemIndices [0] = item and order. id = 11 select item from Item item, Order orderwhere order. items [maxindex (order. items)] = item and order. id = 11
6. order by clause
The list returned by the query can be sorted by any attribute of the class or component attribute, for example:
from Person as p order by p.name, p.age
You can also use the asc or desc keyword to specify the sort rules in ascending or descending order. For example:
from Person as p order by p.name asc , p.age desc
If no sorting rule is specified, the ascending rule is used by default. That is, there is no difference whether the asc keyword is used. Adding asc is in ascending order, and without asc, it is also in ascending order.
7. group by clause
The query that returns the clustering value can group the attributes of persistence classes or component attributes. The group by clause is used by the grouping. See the following HQL query statement:
select cat.color, sum(cat.weight), count(cat) from Cat cat group by cat.color
The having clause is used to filter groups as follows:
select cat.color, sum(cat.weight), count(cat) from Cat catgroup by cat.color having cat.color in (eg.Color.TABBY, eg.Color.BLACK)
Note: The having clause is used to filter groups. Therefore, the having clause can only be used when a group by clause is available. Without the group by clause, the having clause cannot be used.