在List属性上使用没有Metamodel的JPA2条件API

时间:2010-08-30 22:36:26

标签: java orm jpa jpa-2.0 criteria-api

如何在不使用元模型类的情况下制定以下JPA2条件查询:

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Employee> cq = cb.createQuery(Employee.class);
    Root<Employee> emp = cq.from(Employee.class);
    cq.where(cb.isEmpty(emp.get(Employee_.projects)));
    cq.select(emp);

我想用:

  cq.where(cb.isEmpty(emp.get("projects")));

但我无法弄清楚如何将路径转换为表达式,这是cb.isEmpty所需要的......

感谢。

1 个答案:

答案 0 :(得分:20)

试试这个:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(Employee.class);
Root emp = cq.from(Employee.class);
cq.where(cb.isEmpty(emp.<List<Project>>get("projects")));
cq.select(emp);

或者,使用Path变量:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(Employee.class);
Root emp = cq.from(Employee.class);
Path<List<Project>> projects = emp.get("projects"));
cq.where(cb.isEmpty(projects);
cq.select(emp);

参考