The Wayback Machine - https://web.archive.org/web/20241105020227/https://www.geeksforgeeks.org/hibernate-query-language/
Open In App

Hibernate – Query Language

Last Updated : 09 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

polymorphicHibernate is a Java framework that makes it easier to create database-interactive Java applications. In HQL, instead of a table name, it uses a class name. As a result, it is a query language that is database-independent.

Hibernate converts HQL queries into SQL queries, which are used to perform database actions. Although Native SQL may be used directly with Hibernate, it is encouraged to utilize HQL wherever feasible to prevent database portability issues.

HQL has many benefits. Some benefits are:

  • HQL is database-independent.
  • polymorphic queries supported which are type-safe.
  • It is portable and easy to learn for Java programmers.

The Query interface provides object-oriented methods and capabilities for representing and manipulating HQL queries.

Note: 1. Keywords like FROM, SELECT, WHERE are not case-sensitive in HQL.
2. Table and Column names are case-sensitive in HQL.

Hibernate Query Language (HQL) Clauses

There are many HQL clauses available to interact with relational databases, and several of them are listed below:

  1. FROM Clause
  2. SELECT Clause
  3. WHERE Clause
  4. ORDER BY Clause
  5. UPDATE Clause
  6. DELETE Clause
  7. INSERT Clause

For details and examples regarding each clause is mentioned below.

1. FROM Clause

To load a whole persistent object into memory, the FROM clause is used.

String hib = "FROM Student";

Query query = session.createQuery(hib);
List results = query.list();

2. SELECT Clause

The SELECT clause is used when only a few attributes of an object are required rather than the entire object.

String hib = "SELECT S.roll FROM Student S";

Query query = session.createQuery(hib);
List results = query.list();

3. WHERE Clause

Filtering records is done with the WHERE clause. It’s used to retrieve only the records that meet a set of criteria.

String hib = "FROM Student S WHERE S.id = 5";

Query query = session.createQuery(hib);
List results = query.list();

4. ORDER BY Clause

The ORDER BY clause is used to sort the results of an HQL query.

String hib = "FROM Student S WHERE S.id > 5 ORDER BY S.id DESC";

Query query = session.createQuery(hib);
List results = query.list();

NOTE:

1. Order By – DESC will sort in descending order

2. Order By – ASC will sort in ascending order

5. UPDATE Clause

The UPDATE clause is required to update the value of an attribute.

String hib = "UPDATE Student set name=:n WHERE roll=:i";

Query q=session.createQuery(hib);
q.setParameter("n","John");
q.setParameter("i",23);

int status=q.executeUpdate();
System.out.println(status);

6. DELETE Clause

It is required to delete a value of an attribute.

String hib = "DELETE FROM Student WHERE id=10";

Query query=session.createQuery(hib);
query.executeUpdate();

7. INSERT Clause

It is required to Insert values into the relation.

String hib = "INSERT INTO Student(first_name, last_name)" +
"SELECT first_name, last_name FROM backup_student";

Query query = session.createQuery(hib);
int result = query.executeUpdate();

Pagination using Query

For pagination using query we have two methods available for it, below table contains the methods and its description.

Method Action Performed
Query setMaxResults(int max) Instructs Hibernate to get a specific number of items.
Query setFirstResult(int starting_no) Takes an integer as an argument that represents the first row in your result set, beginning with row 0.

Example for pagination using HQL

To fetch the few row data at a time we can use pagination using HQL. For this example we are fetching the rows 5 to 10.

String hib = "FROM Student"

Query query=session.createQuery(hib);
query.setFirstResult(5);
query.setMaxResult(10);

List list=query.list();

The above example returns the list of records from 5 to 10.

Aggregate Methods

Similar to SQL, HQL has several aggregation techniques, some of them are mentioned below-

  • Average
  • Max
  • Min
  • Count
  • Sum

For details and examples regarding each aggregate method is mentioned below.

Average

To find the average of marks

String hib = "SELECT AVG(marks) FROM Student";
Query q=session.createQuery(hib);

Max

To find the maximum mark among all the available marks.

String hib = "SELECT MAX(marks) FROM Student";
Query q=session.createQuery(hib);

Min

To find the minimum mark among all the available marks.

String hib = "SELECT MIN(marks) FROM Student";
Query q=session.createQuery(hib);

Count

To find the count of id present.

String hib = "SELECT COUNT(id) FROM Student";
Query q=session.createQuery(hib);

NOTE: For counting only distinct values you can use DISTINCT in the following ways-
1. With the SELECT clause as “SELECT DISTINCT name FROM Student”
2. With the FROM clause (deprecated) as “SELECT * FROM DISTINCT Student”

Sum

To find the sum of all the marks of Student.

String hib = "SELECT SUM(marks) FROM Student";

Query q=session.createQuery(hib);

List<Integer> list=q.list();
System.out.println(list.get(0));

Conclusion

Overall, this article has provided a detailed explanation for Hibernate Query Language (HQL), a tool building a bridge of communication with any relational databases in Java applications. By utilizing HQL, developers can achieve various benefits:

  • Database independence and portability
  • write type-safe queries.
  • Benefits from object-oriented features like the Query interface

As discussed in the above examples, HQL offers a range of clauses for various use cases:

  • Manipulating data including
    • FROM
    • SELECT
    • WHERE
    • ORDER BY
    • UPDATE
    • DELETE
    • INSERT
  • Additionally, it also provides various aggregation methods like
    • average
    • maximum
    • minimum
    • count
    • sum
    • enabling efficient data analysis

Overall, mastering HQL can significantly enhance the efficiency and maintainability of Java applications that interact with relational databases.



Previous Article
Next Article

Similar Reads

Hibernate - Create Hibernate Configuration File with the Help of Plugin
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is a java framework that is used to develop persisten
3 min read
Hibernate Native SQL Query with Example
Hibernate is a popular object-relational mapping (ORM) tool used in Java applications. It allows developers to map Java objects to database tables and perform CRUD (create, read, update, delete) operations on the database without writing SQL queries manually. Native SQL queries are useful when you need to perform complex queries that cannot be expr
7 min read
Query String and Query Parameter in Spring MVC
According to Wikipedia "A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML, choosing the appearance of a page, or jumping to positions in multimedia content."
6 min read
Hibernate - Annotations
Annotation in JAVA is used to represent supplemental information. As you have seen @override, @inherited, etc are an example of annotations in general Java language. For deep dive please refer to Annotations in Java. In this article, we will discuss annotations referred to hibernate. So, the motive of using a hibernate is to skip the SQL part and f
7 min read
Introduction to Hibernate Framework
Prerequisite : JDBC Need of Hibernate Framework Hibernate is used to overcome the limitations of JDBC like: JDBC code is dependent upon the Database software being used i.e. our persistence logic is dependent, because of using JDBC. Here we are inserting a record into Employee table but our query is Database software-dependent i.e. Here we are usin
4 min read
Hibernate - Cache Eviction with Example
Caching in Hibernate means storing and reusing frequently used data to speed up your application. There are two kinds of caching: Session-level and SessionFactory-level. Level 1 cache is a cache that stores objects that have been queried and persist to the current session. This cache helps to reduce the number of database round trips by storing obj
9 min read
Hibernate - Bag Mapping
For a multi-national company, usually, selections are happened based on technical questions/aptitude questions. If we refer to a question, each will have a set of a minimum of 4 options i.e each question will have N solutions. So we can represent that by means of "HAS A" relationship i.e. 1 question has 4 solutions. Via Bag Mapping, in Hibernate, w
4 min read
Difference between JDBC and Hibernate in Java
Java is one of the most powerful and popular server-side languages in the current scenario. One of the main features of a server-side language is the ability to communicate with the databases. In this article, let's understand the difference between two ways of connecting to the database (i.e.) JDBC and Hibernate. Before getting into the difference
2 min read
Hibernate Example using XML in Eclipse
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. In this article, let us see a Hibernate Example using XM
6 min read
Hibernate Lifecycle
Here we will learn about Hibernate Lifecycle or in other words, we can say that we will learn about the lifecycle of the mapped instances of the entity/object classes in hibernate. In Hibernate, we can either create a new object of an entity and store it into the database, or we can fetch the existing data of an entity from the database. These enti
4 min read
Java - JPA vs Hibernate
JPA stands for Java Persistence API (Application Programming Interface). It was initially released on 11 May 2006. It is a Java specification that gives some functionality and standard to ORM tools. It is used to examine, control, and persist data between Java objects and relational databases. It is observed as a standard technique for Object Relat
4 min read
Spring Boot - Integrating Hibernate and JPA
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Hibernate - Difference Between ORM and JDBC
Hibernate is a framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas Hibernate framework we use Objects to develop persistence logic that is independent of database software. ORM (Object-Relational Mapping) ORM, an abbreviation for Ob
4 min read
Hibernate - Generator Classes
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas in Hibernate framework we use Objects to develop persistence logic that is independent of
5 min read
Hibernate - Create POJO Classes
POJO stands for Plain Old Java Object. In simple terms, we use POJO to make a programming model for declaring object entities. The classes are simple to use and do not have any restrictions as compared to Java Beans. To read about POJO classes and Java Bean refer to the following article - POJO classes and Java Bean POJO is handier as its best in r
3 min read
Hibernate - One-to-One Mapping
Prerequisite: Basic knowledge of hibernate framework, Knowledge about databases, Java Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to
15 min read
Hibernate - SQL Dialects
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. An ORM(Object-relational mapping) framework simplifies data creation, data manipulation, and data access. It is a programming technique that maps the object to the d
3 min read
Hibernate - Web Application
A web application with hibernate is easier. A JSP page is the best way to get user inputs. Those inputs are passed to the servlet and finally, it is inserted into the database by using hibernate. Here JSP page is used for the presentation logic. Servlet class is meant for the controller layer. DAO class is meant for database access codes. Tools and
9 min read
Hibernate - Table Per Concrete Class using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
5 min read
Hibernate - Table Per Subclass using Annotation
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. An ORM(Object-relational mapping) framework simplifies data creation, data manipulation, and data access. It is a programming technique that maps the object to the d
6 min read
Hibernate - Table Per Hierarchy using XML File
Hibernate is capable of storing the inherited properties of an object along with its new properties in its database when an object is saved in the database. In Hibernate, inheritance between POJO classes is applied when multiple POJO classes of a module contain some common properties. In a real-time application, POJO classes of Hibernate are design
6 min read
Hibernate - Table Per Subclass Example using XML File
In Table Per Subclass, subclass tables are mapped to the Parent class table by primary key and foreign key relationship. In a Table per Subclass strategy : For each class of hierarchy there exist a separate table in the database.While creating the database tables foreign key relationship is required between the parent table and the child table.To p
5 min read
Hibernate - Criteria Queries
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. To get the data available in RDBMS tables, Hibernate fol
12 min read
Hibernate - Table Per Hierarchy using Annotation
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, it does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is an open-source, non-invasive, lightweight java ORM(Object
8 min read
Hibernate - Types of Mapping
Hibernate is a Java framework that simplifies the development of Java applications to interact with the database. It is an open-source, lightweight, ORM (Object Relational Mapping) tool. Hibernate implements the specifications of JPA (Java Persistence API) for data persistence. There are different relations that we maintain to establish a link betw
2 min read
Hibernate - Many-to-Many Mapping
In RDBMS, we can see a very common usage of parent-child relationships. It can be achieved in Hibernate via One-to-many relationshipMany-to-one relationshipOne-to-one relationshipMany-to-many relationship Here we will be discussing how to perform Hibernate - Many-to-Many mappings. Below are the example tables to demonstrate Many-to-Many mappings as
12 min read
Hibernate - Interceptors
Interceptors are used in conjunction with Java EE managed classes to allow developers to invoke interceptor methods on an associated target class, in conjunction with method invocations or lifecycle events. Common uses of interceptors are logging, auditing, and profiling. The Interceptors 1.1 specification is part of the final release of JSR 318, E
6 min read
Hibernate - Table Per Concrete Class Using Annotation
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, it does the implementations for you internally like writing queries to perform CRUD operations, establishing a connection with the database, etc. It is an open-source, non-invasive, lightweight java ORM(Object
7 min read
Hibernate - Logging By Log4j Using Properties File
Apache log4j is a java-based logging utility. Apache log4j role is to log information to help applications run smoothly, determine what’s happening, and debug processes when errors occur. log4j may logs login attempts (username, password), submission form, and HTTP headers (user-agent, x-forwarded-host, etc.) into the log file or database. Apache l
2 min read
Hibernate - Many-to-One Mapping
Hibernate is an open-source, ORM(Object Relational Mapping) framework that provides CRUD operations in the form of objects. It is a non-invasive framework. It can be used to develop DataAcessLayer for all java projects. It is not server-dependent. It means hibernate code runs without a server and with a server also. It is a top layer of JDBC, JTA,
5 min read
Practice Tags :
three90RightbarBannerImg