Video in progress
What is JPQL and how does it differ from SQL?
JPQL is a query language written against entities and their fields; Hibernate translates it into the database's SQL dialect. SQL works with table and column names, while JPQL works with class names and Java field names.
📖 Answer
// JPQL: class name and field name
List<Employee> list = em.createQuery(
"select e from Employee e where e.department.name = :dep", Employee.class)
.setParameter("dep", "IT")
.getResultList();
The SQL for the same thing is roughly:
select e.* from employees e
join departments d on d.id = e.department_id
where d.name = 'IT'
In JPQL you didn't write the join condition: Hibernate added the join itself through the e.department path.
Differences:
- JPQL is database-independent: if you move from PostgreSQL to MySQL, the query doesn't change;
- the result is entities, and they land in the persistence context;
- database-specific features (for example, PostgreSQL's
jsonboperators, some window functions) may not exist in JPQL, and then you use a native query.
HQL is Hibernate's broader version of JPQL. In Hibernate 6 HQL got much richer: CTEs, union and more functions were added. That is not standard in JPA.
Sign up to mark studied questions and save your progress.