Nickname11
Nickname11

Reputation: 571

Hibernate CriteriaQuery where - ManyToOne field

that's fragment of my Employee entity/class:

@Entity
@Table
public class Employee {
   ...
   @ManyToOne(.....)
   @JoinColumn(name="department_id")
   private Department department;
}

Now, I want to fetch all Employees from specific Department (employees with specific department_id):

CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Employee> criteriaQuery = builder.createQuery(Employee.class);
Root<Employee> employeeRoot = criteriaQuery.from(Employee.class);

criteriaQuery.select(employeeRoot);
criteriaQuery.where(builder.equal(employeeRoot.get(????????????), id));

There's my problem. How do I access Department.id? I know i have to get({specific field}) but i dunno how. Should I somehow join those tables first? Looking forward for your answers!

Upvotes: 0

Views: 672

Answers (1)

Wanderson Mendes
Wanderson Mendes

Reputation: 196

You need create a join with your relationed table. Ex:

CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Employee> criteriaQuery = builder.createQuery(Employee.class);
Root<Employee> employeeRoot = criteriaQuery.from(Employee.class);

Join<Employee, Departament> join = from.join("department", JoinType.INNER);
criteriaQuery.where(builder.equal(join.get("specific_fied"), your_specific_fied));

TypedQuery<Employee> typedQuery = session.createQuery(criteriaQuery);

List<Employee> employees = typedQuery.getResultList();
for (Employee e : employees) {
    System.out.println(e.getName());
}

session.getTransaction().commit();
session.close();
entityManagerFactory.close();

If you want anything same as this query:

SELECT c, p.name FROM Country c LEFT OUTER JOIN c.capital p

you can build this:

  CriteriaQuery<Country> q = cb.createQuery(Country.class);
  Root<Country> c = q.from(Country.class);
  Join<Country> p = c.join("capital", JoinType.LEFT);
  q.multiselect(c, p.get("name"));

If you what build anything same as this query:

SELECT c FROM Country c JOIN FETCH c.capital

you can build this:

  CriteriaQuery<Country> q = cb.createQuery(Country.class);
  Root<Country> c = q.from(Country.class);
  Fetch<Country,Capital> p = c.fetch("capital");
  q.select(c);

For more exemples see FROM clause (JPQL / Criteria API)

Upvotes: 2

Related Questions