Sobes.tech
Junior — Middle

How to implement table joins using HQL?

sobes.tech AI

Answer from AI

In HQL (Hibernate Query Language), the keyword join is used to combine tables. HQL works with objects and their associations, not directly with tables, so the join occurs through relationships between entities.

Example of joining two entities Employee and Department via the department association:

String hql = "SELECT e FROM Employee e JOIN e.department d WHERE d.name = :deptName";
Query query = session.createQuery(hql);
query.setParameter("deptName", "IT");
List<Employee> employees = query.list();

Here, JOIN e.department d joins the Employee entity with the related Department entity. You can also use LEFT JOIN or INNER JOIN depending on the task.

If you need to join based on a condition not directly linked through object associations, you can use JOIN with ON in newer versions of HQL, but it is more common to model relationships within entities.