Criteria Builder Create new Object In Select State

2019-03-15 04:35发布

I was wondering if it's possible to create such query like :

em.createQuery(
        "SELECT NEW EmpMenu(p.name, p.department.name) "
            + "FROM Project p ").getResultList();

also is it possible to do it via Specification:

public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
        CriteriaBuilder cb) {


    return ???;
}

Thanks in advance!

1条回答
虎瘦雄心在
2楼-- · 2019-03-15 05:18

Yes, Criteria API does have have construct similar to JPQL constructor expressions. Resuls class is set via construct method in CriteriaBuilder.

Your JPQL query expressed as an criteria query is:

CriteriaBuilder cb...
CriteriaQuery<EmpMenu> q = cb.createQuery(EmpMenu.class);
  Root<Project> c = q.from(Project.class);
  q.select(cb.construct(EmpMenu.class,
      c.get("name"), c.get("department").get("name")));
查看更多
登录 后发表回答