这是我的员工实体/类的片段:
@Entity
@Table
public class Employee {
...
@ManyToOne(.....)
@JoinColumn(name="department_id")
private Department department;
}
现在,我想从特定部门获取所有员工(具有特定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));
这是我的问题。如何访问Department.id?我知道我必须得到({特定领域}(,但我不知道怎么做。我应该先加入那些桌子吗?期待您的回答!
您需要创建一个与关系表的联接。例如:
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();
如果您想要与此查询相同的内容:
SELECT c, p.name FROM Country c LEFT OUTER JOIN c.capital p
你可以构建这个:
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"));
如果你构建了与这个查询相同的东西:
SELECT c FROM Country c JOIN FETCH c.capital
你可以构建这个:
CriteriaQuery<Country> q = cb.createQuery(Country.class);
Root<Country> c = q.from(Country.class);
Fetch<Country,Capital> p = c.fetch("capital");
q.select(c);
有关更多示例,请参见FROM子句(JPQL/Ccriteria API(