Hibernate CriteriaQuery where - ManyToOne 字段
Posted
技术标签:
【中文标题】Hibernate CriteriaQuery where - ManyToOne 字段【英文标题】:Hibernate CriteriaQuery where - ManyToOne field 【发布时间】:2020-04-24 20:52:42 【问题描述】:这是我的 Employee 实体/类的片段:
@Entity
@Table
public class Employee
...
@ManyToOne(.....)
@JoinColumn(name="department_id")
private 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?我知道我必须得到(特定字段),但我不知道如何。我应该先以某种方式加入这些表格吗?期待您的回答!
【问题讨论】:
【参考方案1】:您需要与您的关联表创建一个联接。 例如:
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 clause (JPQL / Criteria API)
【讨论】:
以上是关于Hibernate CriteriaQuery where - ManyToOne 字段的主要内容,如果未能解决你的问题,请参考以下文章