JPQL

About

JPQL is the object-oriented query language defined by the Java Persistence API (JPA). It’s similar in syntax to SQL but operates on the entity object model rather than directly on database tables.

  • SQL works on tables, rows, columns.

  • JPQL works on entities, fields, relationships.

Some of the Features of JPQL

  • Queries entities and their relationships using object-based syntax.

  • Supports CRUD operations using HQL-like statements.

  • Abstracts underlying SQL and RDBMS-specific queries.

  • Enables navigation across entity relationships like @OneToMany, @ManyToOne.

  • Strongly integrated with JPA EntityManager.

JPQL Query Types

1. Basic SELECT

Fetch entities or specific fields from a table (entity).

TypedQuery<Employee> query = em.createQuery(
  "SELECT e FROM Employee e", Employee.class);
List<Employee> result = query.getResultList();

Fetch all employees from the database.

2. SELECT with WHERE Clause

Find all employees in the Finance department.

3. Selecting Specific Fields (Projection)

Fetch just the names of all employees.

Or multiple fields:

4. Using Aggregate Functions

Get average salary across all employees.

5. GROUP BY and HAVING

Find departments with more than 5 employees.

6. JOINs (Entity Relationships)

JPQL handles joins using entity fields, not tables.

Get projects where John Doe is assigned.

7. ORDER BY Clause

List employees sorted by salary (highest first).

8. IN Clause

Get employees from IT or HR.

9. LIKE Clause (Pattern Matching)

Find employees whose name starts with 'A'.

10. Subqueries

Get employees earning above the average salary.

11. UPDATE and DELETE

JPQL supports UPDATE and DELETE, but not INSERT.

UPDATE

Give 10% raise to IT department.

DELETE

Remove all inactive employees.

12. Constructor Expressions (DTO Projection)

Return results in a custom DTO.

Limitations of JPQL

  • No support for INSERT.

  • Complex SQL (window functions, full joins, recursive CTEs) not supported.

  • Limited database-specific syntax (must switch to native queries).

Last updated