Hibernate CRUD example using HQL

Hibernate Query Language (HQL) is an object query language provided by Hibernate to manipulate data held in databases. It is inspired by SQL but instead of working directly with tables It uses persistent objects.

In this example, we will perform some useful database operations, known as CRUD, using Hibernate HQL statements such as insert, update, delete..etc.


1. Technologies used

  • Hibernate 4.3.6.Final
  • MySQL 5.1
  • Maven 3.0.5
  • Eclipse 4.5
  • JDK 1.7


2. Database table

We crate a database table PRODUCT.


3. Project structure



4. Model class

File : src/main/java/com/keylesson/persistence/Product.java


5. Mapping file

File : src/main/resources/com/keylesson/persistence/Product.hbm.xml


6. Hibernate configuration file

File : src/main/resources/hibernate.cfg.xml


7. Hibernate Utility

Build the sessionFactory and get a session instance.


8. HQL CRUD operations

The first operation : adding three records to table PRODUCT.


Second operation : listing PRODUCT records using restriction on the unitPrice column.


Third operation : changing value of quantity and discontinued columns in the second record.


Fourth operation : removing the third record.


One more operation : using insert statement to copy the PRODUCT content to another table that we will call OTHER_PRODUCT (which has the same structure, model class and mapping file as PRODUCT table…just to make it easy to test)

Notice that, unlike ordinary SQL, the insert statement can only be used to insert entities constructed from information obtained from select queries. In other words, we cannot specify values to insert.


9. Test It

Output :


Download source code