简体   繁体   English

使用具有 jpa 规格的 spring 数据按特定顺序按多个值排序

[英]Sort by multiple values in specific order using spring data with jpa specifications

I have a query我有一个问题

select * from docs
where status_id in ('105', '55', '65', '228016')
order by
case status_id
    when '55' then 1
    when '228016' then 2
    when '65' then 3
    when '105' then 4
end;

How to rewrite it in spring data with specifications?如何在spring数据中改写规范?

p2 = repository.findAll(new DocsRepository.DocsSpec(filter, type), 
PageRequest.of(page, size, Sort.by(Sort.Order.desc("status"))));

This answer helped me这个答案帮助了我

  1. Created OrderByField class创建OrderByField class

     import javax.persistence.criteria.Expression; import javax.persistence.criteria.Order; public class OrderByField implements Order { private Expression<?> expression; public OrderByField(Expression<?> expression) { this.expression = expression; } @Override public Order reverse() { return null; } @Override public boolean isAscending() { return true; } @Override public Expression<?> getExpression() { return expression; } }
  2. Created expression with criteriaBuilder's selectCase function使用 criteriaBuilder 的 selectCase 创建表达式 function

     Expression searchedCaseExpression = criteriaBuilder.selectCase().when(criteriaBuilder.equal(root.get("status").get("code"), "55"), "1").when(criteriaBuilder.equal(root.get("status").get("code"), "228016"), "2").when(criteriaBuilder.equal(root.get("status").get("code"), "65"), "3").when(criteriaBuilder.equal(root.get("status").get("code"), "105"), "4"); OrderByField order = new OrderByField(searchedCaseExpression); criteriaQuery.orderBy(order);

And don't forget to remove Sort.by from findAll(), since we're sorting with criteriaBuilder并且不要忘记从 findAll() 中删除 Sort.by,因为我们正在使用 criteriaBuilder 进行排序

    p2 = repository.findAll(new DocsRepository.DocsSpec(filter, type), PageRequest.of(page, size));

And one more thing, although JPA 2.x supports CASE in JPQL it is not supported in ORDER BY clauses.还有一件事,尽管 JPA 2.x 在 JPQL 中支持 CASE,但在 ORDER BY 子句中不支持。 This might go unnoticed, though, as Hibernate's implementation of JPQL, for instance, does support CASE in ORDER BY不过,这可能 go 未被注意到,因为例如,Hibernate 的 JPQL 实现确实支持 ORDER BY 中的 CASE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM