The most preferred way is using the Hibernate Query Language (HQL), which is an easy-to-learn and powerful query language, designed as a minimal object-oriented extension to SQL. HQL has syntax and keywords/clauses very similar to SQL. It also supports many other SQL-like features, such as aggregate functions (for example: sum(), max()) and clauses such as group by and order by clause.
Clause | Description | Syntax | Example |
from | The simplest form of an HQL query. Specifies the object whose instances are to be returned as the query result. Commonly used with the select clause. | from object [as object_alias]* object_alias simply means another name given to refer to an object for convenience. | from UserDetails as user
Will return all instances of object UserDetails. |
select | Specifies objects and properties to be returned in the query result set. Used in conjunction with the from clause. | select [object.]property | select user.userName from UserDetails as user
Will return all values of userName in all instances of UserDetails. |
where | Specifies the conditions that should be satisfied by the instances returned as the query result. Used with select and/or from clause. | where condition
Here, condition is a combination of logical, relational operators i.e. =, >, AND, NOT etc. |
from UserDetails as user where user.userId > 2 Will return all instances of user in UserDetails whose correspondinguser.userId values are greater than 2. |
order by | Specifies the order (ascending/descending) in which the properties of objects returned as query results should be listed. Used with the select and from clauses. | order by object0.property0 [asc|desc][, object1.property0]…
By default, order is ascending unless specified otherwise. |
from UserDetails as user order by userId asc
Will return a list of all instances of user in ascending order of corresponding userId values. |
group by | Specifies the grouping criteria using objects properties, by which the list of objects returned as a query result should be grouped together. Used with the select and/or from clause. | group by object0.property0[, object1.property0]… | select userId from UserDetails as user group by user.userId
Will return list of all userId instances from user grouped by corresponding values of user. |
In the Next Chapter we will discuss about the How work Pagination in Hibernate Query Language(HQL).
<<Previous Chapter 25<< >>Next Chapter 27>>