JPA 标准查询 API 和按两列排序

2022-08-31 15:52:47

我陷入了一个简单的问题;挣扎如何在ed实体上调用。从本质上讲,我正试图通过以下方式实现以下目标:order byjoinJPA Criteria

select distinct d from Department d 
left join fetch d.children c 
left join fetch c.appointments a
where d.parent is null 
order by d.name, c.name

我有以下几点:

CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Department> c = cb.createQuery(Department.class);
Root<Department> root = c.from(Department.class);
Fetch<Department, Department> childrenFetch = root.fetch(
    Department_.children, JoinType.LEFT);
childrenFetch.fetch(Department_.appointments, JoinType.LEFT);

c.orderBy(cb.asc(root.get(Department_.name)));
c.distinct(true);
c.select(root);
c.where(cb.isNull(root.get(Department_.parent)));

如何实现?我尝试使用表达式,路径,但不起作用。任何指针将不胜感激。order by d.name, c.nameCriteria API


答案 1

如果您需要添加几个订单,则可以创建类似的东西(但对于您的查询和不同的根对象)

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Route> query = criteriaBuilder.createQuery(Route.class);
Root<Route> routeRoot = query.from(Route.class);
query.select(routeRoot);

List<Order> orderList = new ArrayList();
query.where(routeRoot.get("owner").in(user));

orderList.add(criteriaBuilder.desc(routeRoot.get("date")));
orderList.add(criteriaBuilder.desc(routeRoot.get("rating")));

query.orderBy(orderList);

答案 2

我使用标准API对订单有同样的问题。我发现了这个解决方案:

CriteriaQuery<Test> q = cb.createQuery(Test.class);
Root<Test> c = q.from(Test.class);
q.select(c);
q.orderBy(cb.asc(c.get("name")), cb.desc(c.get("prenom")));

推荐