S02L02 – Hibernate HQL operation – Where clause


Hibernate HQL Operation – WHERE Clause

Table of Contents

  1. Introduction
  2. Understanding HQL and WHERE Clause
  3. Code Implementation
  4. Code Walkthrough
  5. Comparison Table
  6. Conclusion

Introduction

Hibernate Query Language (HQL) is a powerful feature of Hibernate that allows developers to perform SQL-like operations on entity objects. The WHERE clause in HQL is used to filter records based on specific conditions, enhancing flexibility when querying databases.

Key Features:

  • HQL is case-insensitive for keywords like FROM, WHERE, etc.
  • Enables object-oriented querying, unlike traditional SQL.

When to Use: The WHERE clause is used when specific records need to be fetched that satisfy certain conditions.

Understanding HQL and WHERE Clause

What is HQL?

Hibernate Query Language (HQL) is an object-oriented query language similar to SQL but operates on entity objects rather than database tables.

Where Clause in HQL

The WHERE clause is used to apply filters in a query. This ensures only specific records are fetched based on the condition provided.

Syntax:

Example:

Code Implementation

Entity Class – Users.java

Main Program – App.java

Code Walkthrough

  • Entity Class: Maps Java class to the database table.
  • Main Class: Retrieves records using the HQL WHERE clause.
  • The session.createQuery() method executes the HQL query.

Output

Assume the database contains the following records:

user_id username password first_name last_name
1 john abc123 John Doe
2 alice xyz123 Alice Smith
3 bob pqr456 Bob Brown

Program Output:

Comparison Table

SQL HQL
Operates on tables and columns Operates on entities and fields
Case-sensitive for table names Case-insensitive for keywords
SELECT * FROM users FROM Users

Conclusion

The WHERE clause in Hibernate HQL is a crucial feature that enables filtering records efficiently. It simplifies database queries while maintaining a clean, object-oriented approach.