Hackforge Academy

Category: java

JPQL (Java Persistence Query Language)

Published on 24 Jul 2026

Explanation

JPQL is an object-oriented query language used to retrieve and manipulate entity objects instead of database tables. It works with entity names and field names, making queries independent of the underlying database.

Code:

@Query("SELECT s FROM Student s WHERE s.department = :department")
List<Student> findByDepartment(String department);

Explanation

Native Queries allow you to execute raw SQL directly against the database. They are useful when using database-specific features, complex joins, stored procedures, or optimized SQL that cannot be easily expressed using JPQL.

Code:

@Query(value = "SELECT * FROM student WHERE age > ?1", nativeQuery = true)
List<Student> findStudentsByAge(int age);

Explanation

Spring Data JPA Specifications help build dynamic queries based on optional search criteria. Instead of writing multiple repository methods, specifications allow filters to be combined at runtime for flexible searching.

Code:

public interface StudentRepository extends
JpaRepository<Student, Long>,
JpaSpecificationExecutor<Student> {
}

Explanation

A Specification defines query conditions using the Criteria API. Multiple specifications can be combined using and() or or() to create complex, reusable, and dynamic database queries without writing custom SQL.

Code:

public static Specification<Student> hasDepartment(String dept) {
    return (root, query, cb) ->
        cb.equal(root.get("department"), dept);
}

Explanation

The Criteria API provides a type-safe and programmatic way to build dynamic queries. It is especially useful when query conditions depend on user input or when constructing complex queries without hardcoded JPQL strings.

Code:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Student> query = cb.createQuery(Student.class);
Root<Student> root = query.from(Student.class);
query.select(root);

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community