Anda di halaman 1dari 11

Hibernate Query Language (HQL) Example http://www.codejava.net/frameworks/hibernate/hibernate-query-languag...

Hibernate Query Language (HQL) Example


Last Updated on 18 February 2016 | Print Email

Java Hosting from just $5/mo. Get it now! Download Aspose for all your file format manipulation needs
The Hibernate ORM framework provides its own query language called Hibernate Query Language or HQL for short. It is very powerful
and flexible and has the following characteristics:

SQL similarity: HQL’s syntax is very similar to standard SQL. If you are familiar with SQL then writing HQL would be pretty easy:
from SELECT, FROM, ORDER BY to arithmetic expressions and aggregate functions, etc.
Fully object-oriented: HQL doesn’t use real names of table and columns. It uses class and property names instead. HQL can
understand inheritance, polymorphism and association.
Case-insensitive for keywords: Like SQL, keywords in HQL are case-insensitive. That means SELECT, select or Select
are the same.
Case-sensitive for Java classes and properties: HQL considers case-sensitive names for Java classes and their
properties, meaning Person and person are two different objects.

In this tutorial, we show you how to write HQL for executing fundamental queries (CRUD) as well as other popular ones. The following
diagram illustrates relationship of the tables used in examples of this tutorial:

And here are the model classes annotated with JPA annotations:

Category class:

1 of 11 4/6/2016 2:06 PM
Hibernate Query Language (HQL) Example http://www.codejava.net/frameworks/hibernate/hibernate-query-languag...
1 package net.codejava.hibernate;
2
3 import java.util.Set;
4
5 import javax.persistence.CascadeType;
6 import javax.persistence.Column;
7 import javax.persistence.Entity;
8 import javax.persistence.GeneratedValue;
9 import javax.persistence.Id;
10 import javax.persistence.OneToMany;
11 import javax.persistence.Table;
12
13
14 @Entity
15 @Table(name = "CATEGORY")
16 public class Category {
17
18 private long id;
19 private String name;
20
21 private Set<Product> products;
22
23 public Category() {
24 }
25
26 public Category(String name) {
27 this.name = name;
28 }
29
30 @Id
31 @Column(name = "CATEGORY_ID")
32 @GeneratedValue
33 public long getId() {
34 return id;
35 }
36
37
38 @OneToMany(mappedBy = "category", cascade = CascadeType.ALL)
39 public Set<Product> getProducts() {
40 return products;
41 }
42
43 // other getters and setters
44 }

Product class:

2 of 11 4/6/2016 2:06 PM
Hibernate Query Language (HQL) Example http://www.codejava.net/frameworks/hibernate/hibernate-query-languag...
1 package net.codejava.hibernate;
2
3 import javax.persistence.Column;
4 import javax.persistence.Entity;
5 import javax.persistence.GeneratedValue;
6 import javax.persistence.Id;
7 import javax.persistence.JoinColumn;
8 import javax.persistence.ManyToOne;
9 import javax.persistence.Table;
10
11 @Entity
12 @Table(name = "PRODUCT")
13 public class Product {
14 private long id;
15 private String name;
16 private String description;
17 private float price;
18
19 private Category category;
20
21 public Product() {
22 }
23
24 public Product(String name, String description, float price,
25 Category category) {
26 this.name = name;
27 this.description = description;
28 this.price = price;
29 this.category = category;
30 }
31
32 @Id
33 @Column(name = "PRODUCT_ID")
34 @GeneratedValue
35 public long getId() {
36 return id;
37 }
38
39 @ManyToOne
40 @JoinColumn(name = "CATEGORY_ID")
41 public Category getCategory() {
42 return category;
43 }
44
45 // other getters and setters
46 }

Order class:

3 of 11 4/6/2016 2:06 PM
Hibernate Query Language (HQL) Example http://www.codejava.net/frameworks/hibernate/hibernate-query-languag...
1 package net.codejava.hibernate;
2
3 import java.util.Date;
4
5 import javax.persistence.Column;
6 import javax.persistence.Entity;
7 import javax.persistence.GeneratedValue;
8 import javax.persistence.Id;
9 import javax.persistence.JoinColumn;
10 import javax.persistence.ManyToOne;
11 import javax.persistence.OneToMany;
12 import javax.persistence.Table;
13 import javax.persistence.Temporal;
14 import javax.persistence.TemporalType;
15
16 @Entity
17 @Table(name = "ORDERS")
18 public class Order {
19 private int id;
20 private String customerName;
21 private Date purchaseDate;
22 private float amount;
23 private Product product;
24
25 @Id
26 @Column(name = "ORDER_ID")
27 @GeneratedValue
28 public int getId() {
29 return id;
30 }
31
32 public void setId(int id) {
33 this.id = id;
34 }
35
36 @Column(name = "CUSTOMER_NAME")
37 public String getCustomerName() {
38 return customerName;
39 }
40
41 @Column(name = "PURCHASE_DATE")
42 @Temporal(TemporalType.DATE)
43 public Date getPurchaseDate() {
44 return purchaseDate;
45 }
46
47
48 @ManyToOne
49 @JoinColumn(name = "PRODUCT_ID")
50 public Product getProduct() {
51 return product;
52 }
53
54 // other getters and setters
55 }

4 of 11 4/6/2016 2:06 PM
Hibernate Query Language (HQL) Example http://www.codejava.net/frameworks/hibernate/hibernate-query-languag...

The upcoming examples are provided based on assumption that a Hibernate’s SessionFactory is opened and a transaction has been
started. You can find more about how to obtain SessionFactory and start a transaction in the tutorial: Building Hibernate
SessionFactory from Service Registry.

The following table of content is provided for your convenience:

1. How to execute HQL in Hibernate


2. List Query Example
3. Search Query Example
4. Using Named Parameters Example
5. Insert - Select Query Example
6. Update Query Example
7. Delete Query Example
8. Join Query Example
9. Sort Query Example
10. Group By Query Example
11. Pagination Query Example
12. Date Range Query Example
13. Using Expressions in Query
14. Using Aggregate Functions in Query

1. How to execute HQL in Hibernate


Basically, it’s fairly simple to execute HQL in Hibernate. Here are the steps:

Write your HQL:

1 String hql = "Your Query Goes Here";

Create a Query from the Session:

1 Query query = session.createQuery(hql);

Execute the query: depending on the type of the query (listing or update), an appropriate method is used:
For a listing query (SELECT):

1 List listResult = query.list();

For an update query (INSERT, UPDATE, DELETE):

5 of 11 4/6/2016 2:06 PM
Hibernate Query Language (HQL) Example http://www.codejava.net/frameworks/hibernate/hibernate-query-languag...
1 int rowsAffected = query.executeUpdate();

Extract result returned from the query: depending of the type of the query, Hibernate returns different type of result set. For example:
Select query on a mapped object returns a list of those objects.
Join query returns a list of arrays of Objects which are aggregate of columns of the joined tables. This also applies for queries
using aggregate functions (count, sum, avg, etc).

Now, let’s go through various concrete examples.

2. List Query Example


The following code snippet executes a query that returns all Category objects:

1 String hql = "from Category";


2 Query query = session.createQuery(hql);
3 List<Category> listCategories = query.list();
4
5 for (Category aCategory : listCategories) {
6 System.out.println(aCategory.getName());
7 }

Note that in HQL, we can omit the SELECT keyword and just use the FROM instead.

3. Search Query Example


The following statements execute a query that searches for all products in a category whose name is ‘Computer’:

1 String hql = "from Product where category.name = 'Computer'";


2 Query query = session.createQuery(hql);
3 List<Product> listProducts = query.list();
4
5 for (Product aProduct : listProducts) {
6 System.out.println(aProduct.getName());
7 }

The cool thing here is Hibernate automatically generates JOIN query between the Product and Category tables behind the scene.
Thus we don’t have to use explicit JOIN keyword:

1 from Product where category.name = 'Computer'

If you are new to Hibernate and want to learn more, read this book: Hibernate Made Easy: Simplified Data Persistence with Hibernate
and JPA (Java Persistence API) Annotations

4. Using Named Parameters Example


You can parameterize your query using a colon before parameter name, for example :id indicates a placeholder for a parameter named
id. The following example demonstrates how to write and execute a query using named parameters:

6 of 11 4/6/2016 2:06 PM
Hibernate Query Language (HQL) Example http://www.codejava.net/frameworks/hibernate/hibernate-query-languag...
1 String hql = "from Product where description like :keyword";
2
3 String keyword = "New";
4 Query query = session.createQuery(hql);
5 query.setParameter("keyword", "%" + keyword + "%");
6
7 List<Product> listProducts = query.list();
8
9 for (Product aProduct : listProducts) {
10 System.out.println(aProduct.getName());
11 }

The above HQL searches for all products whose description contains the specified keyword:

1 from Product where description like :keyword

Then use the setParameter(name, value) method to set actual value for the named parameter:

1 query.setParameter("keyword", "%" + keyword + "%");

Note that we want to perform a LIKE search so the percent signs must be used outside the query string, unlike traditional SQL.

5. Insert - Select Query Example


HQL doesn’t support regular INSERT statement (you know why - because the session.save(Object) method does it perfectly). So
we can only write INSERT … SELECT query in HQL. The following code snippet executes a query that inserts all rows from Category
table to OldCategory table:

1 String hql = "insert into Category (id, name)"


2 + " select id, name from OldCategory";
3
4 Query query = session.createQuery(hql);
5
6 int rowsAffected = query.executeUpdate();
7 if (rowsAffected > 0) {
8 System.out.println(rowsAffected + "(s) were inserted");
9 }

Note that HQL is object-oriented, so Category and OldCategory must be mapped class names (not real table names).

6. Update Query Example


The UPDATE query is similar to SQL. The following example runs a query that updates price for a specific product:

1 String hql = "update Product set price = :price where id = :id";


2
3 Query query = session.createQuery(hql);
4 query.setParameter("price", 488.0f);
5 query.setParameter("id", 43l);
6
7 int rowsAffected = query.executeUpdate();
8 if (rowsAffected > 0) {
9 System.out.println("Updated " + rowsAffected + " rows.");
10 }

7. Delete Query Example


Using DELETE query in HQL is also straightforward. For example:

7 of 11 4/6/2016 2:06 PM
Hibernate Query Language (HQL) Example http://www.codejava.net/frameworks/hibernate/hibernate-query-languag...
1 String hql = "delete from OldCategory where id = :catId";
2
3 Query query = session.createQuery(hql);
4 query.setParameter("catId", new Long(1));
5
6 int rowsAffected = query.executeUpdate();
7 if (rowsAffected > 0) {
8 System.out.println("Deleted " + rowsAffected + " rows.");
9 }

8. Join Query Example


HQL supports the following join types (similar to SQL):

inner join (can be abbreviated as join).


left outer join (can be abbreviated as left join).
right outer join (can be abbreviated as right join).
full join

For example, the following code snippet executes a query that retrieves results which is a join between two tables Product and
Category:

1 String hql = "from Product p inner join p.category";


2
3 Query query = session.createQuery(hql);
4 List<Object[]> listResult = query.list();
5
6 for (Object[] aRow : listResult) {
7 Product product = (Product) aRow[0];
8 Category category = (Category) aRow[1];
9 System.out.println(product.getName() + " - " + category.getName());
10 }

Using the join keyword in HQL is called explicit join. Note that a JOIN query returns a list of Object arrays, so we need to deal with
the result set differently:

1 List<Object[]> listResult = query.list();

HQL provides with keyword which can be used in case you want to supply extra join conditions. For example:

1 from Product p inner join p.category with p.price > 500

That joins the Product and Category together with a condition specifies that product’s price must be higher than 500.

As stated earlier, we can write implicit join query which uses dot-notation. For example:

1 from Product where category.name = 'Computer'

That result in inner join in the resulting SQL statement.

9. Sort Query Example


Sorting in HQL is very similar to SQL using ORDER BY clause follows by a sort direction ASC (ascending) or DESC (descending). For
example:

8 of 11 4/6/2016 2:06 PM
Hibernate Query Language (HQL) Example http://www.codejava.net/frameworks/hibernate/hibernate-query-languag...
1 String hql = "from Product order by price ASC";
2
3 Query query = session.createQuery(hql);
4 List<Product> listProducts = query.list();
5
6 for (Product aProduct : listProducts) {
7 System.out.println(aProduct.getName() + "\t - " + aProduct.getPrice());
8 }

That lists all products by the ascending order of price.

10. Group By Query Example


Using GROUP BY clause in HQL is similar to SQL. The following query summarizes price of all products grouped by each category:

1 select sum(p.price), p.category.name from Product p group by category

And here is the code snippet:

1 String hql = "select sum(p.price), p.category.name from Product p group by category";


2
3 Query query = session.createQuery(hql);
4 List<Object[]> listResult = query.list();
5
6 for (Object[] aRow : listResult) {
7 Double sum = (Double) aRow[0];
8 String category = (String) aRow[1];
9 System.out.println(category + " - " + sum);
10 }

11. Pagination Query Example


To return a subset of a result set, the Queryinterface has two methods for limiting the result set:

setFirstResult(int firstResult): sets the first row to retrieve.


setMaxResults(int maxResults): sets the maximum number of rows to retrieve.

For example, the following code snippet lists first 10 products:

1 String hql = "from Product";


2
3 Query query = session.createQuery(hql);
4 query.setFirstResult(0);
5 query.setMaxResults(10);
6
7 List<Product> listProducts = query.list();
8
9 for (Product aProduct : listProducts) {
10 System.out.println(aProduct.getName() + "\t - " + aProduct.getPrice());
11 }

12. Date Range Query Example


A nice feature of Hibernate is that it is able to defer parameter type to generate the resulting SQL statement accordingly. So using date
time parameters in HQL is quick and easy, for example:

9 of 11 4/6/2016 2:06 PM
Hibernate Query Language (HQL) Example http://www.codejava.net/frameworks/hibernate/hibernate-query-languag...
1 String hql = "from Order where purchaseDate >= :beginDate and purchaseDate <= :endDate";
2
3 Query query = session.createQuery(hql);
4
5 SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
6 Date beginDate = dateFormatter.parse("2014-11-01");
7
8 query.setParameter("beginDate", beginDate);
9
10 Date endDate = dateFormatter.parse("2014-11-22");
11 query.setParameter("endDate", endDate);
12
13 List<Order> listOrders = query.list();
14
15 for (Order anOrder : listOrders) {
16 System.out.println(anOrder.getProduct().getName() + " - "
17 + anOrder.getAmount() + " - "
18 + anOrder.getPurchaseDate());
19 }

The above query lists only orders whose purchase date is in a specified range.

13. Using Expressions in Query


For expressions used in the WHERE clause, HQL supports all basic arithmetic expressions similar to SQL include the following:

mathematical operators: +, -, *, /
binary comparison operators: =, >=, <=, <>, !=, like
logical operators: and, or, not
etc

For a complete list of expressions supported by Hibernate, click here.

For example, the following query returns only products with price is ranging from 500 to 1000 dollars:

1 from Product where price >= 500 and price <= 1000

14. Using Aggregate Functions in Query


HQL supports the following aggregate functions:

avg(…), sum(…), min(…), max(…)


count(*)
count(…), count(distinct…), count(all…)

For example, the following query counts all products:

1 select count(name) from Product

And here’s the code snippet that shows how to extract the result:

1 String hql = "select count(name) from Product";


2
3 Query query = session.createQuery(hql);
4 List listResult = query.list();
5 Number number = (Number) listResult.get(0);
6 System.out.println(number.intValue());

You may be also interested in:


Writing a basic Hibernate-based program with Eclipse

10 of 11 4/6/2016 2:06 PM
Hibernate Query Language (HQL) Example http://www.codejava.net/frameworks/hibernate/hibernate-query-languag...
Getting Started With Hibernate Annotations
Hibernate Basics - 3 ways to delete an entity from the datastore
JDBC Tutorial: SQL Insert, Select, Update, and Delete Examples

References
HQL: The Hibernate Query Language
Query interface Javadoc

Share this article:

Free Java Tutorial Videos:


EMAIL ADDRESS: FIRST NAME:

SEND ME

Attachments:
HibernateQueryTest.zip [Eclipse-Maven Project] 21 kB

11 of 11 4/6/2016 2:06 PM

Anda mungkin juga menyukai