Hibernate Query Language (HQL) Example
Hibernate Query Language (HQL) Example
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.
Execute the query: depending on the type of the query (listing or update), an appropriate method is used:
For a listing query (SELECT):
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).
Note that in HQL, we can omit the SELECT keyword and just use the FROM instead.
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:
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
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:
Then use the setParameter(name, value) method to set actual value for the named parameter:
Note that we want to perform a LIKE search so the percent signs must be used outside the query string, unlike traditional SQL.
Note that HQL is object-oriented, so Category and OldCategory must be mapped class names (not real table names).
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 }
For example, the following code snippet executes a query that retrieves results which is a join between two tables Product and
Category:
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:
HQL provides with keyword which can be used in case you want to supply extra join conditions. For example:
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:
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 }
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.
mathematical operators: +, -, *, /
binary comparison operators: =, >=, <=, <>, !=, like
logical operators: and, or, not
etc
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
And here’s the code snippet that shows how to extract the result:
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
SEND ME
Attachments:
HibernateQueryTest.zip [Eclipse-Maven Project] 21 kB
11 of 11 4/6/2016 2:06 PM