按列使用 Spring 中的规范进行排序

huangapple go评论82阅读模式
英文:

Sort by column using Specification in Spring

问题

我在如何按另一张表中实体的计数来对列进行排序方面陷入了两难境地。

我有两个实体

@Entity 
public class Plan {

   Long id;
   String name;
   PlanStatus status;
   LocalDateTime dateCreated;
   LocalDateTime lastUpdated;
}
@Entity 
public class Subscription {
   Long id;
   Plan plan;

目前,我只是直接为使用Pagable(pageRequest)实现的存储库传递了Sort sort

return smsPlanRepository.findAll(planSpecification, pageRequest);

但是否有一种方法可以在每个PlanSubcriber数量上使用Specification进行排序?

public Specification<Plan> hasSort(String sortBy) {
	return (root, query, criteriaBuilder) -> {
	
		return //按订阅者中的Plan计数
	}
}

提前感谢您的帮助!

英文:

I have a dilemma on how to sort a column by the count of an entity from another table.

I have two entities

@Entity 
public class Plan {

   Long id;
   String name;
   PlanStatus status;
   LocalDateTime dateCreated;
   LocalDateTime lastUpdated;
}
@Entity 
public class Subscription {
   Long id;
   Plan plan;

Right now, I just directly passed the Sort sort for the repository implemented with Pagable (pageRequest)
return smsPlanRepository.findAll(planSpecification, pageRequest);

But is there a way where I could use Specification with the number of Subcriber of each Plan?

public Specification&lt;Plan&gt; hasSort(String sortBy) {
	return (root, query, criteriaBuilder) -&gt; {
	
		return //count of by Plan in Subscribers
	}
}

Thank you for your help in advance!

答案1

得分: 1

除了可分页的接口外,Spring规范还可以通过criteriaBuilder API来实现排序,如下所示:

public Specification<Plan> hasSort(String sortBy) {
    return (root, query, criteriaBuilder) -> {
    
        query.multiselect(root.get("fields..."),
                criteriaBuilder.count(root.get("count_field")));

        query.orderBy(criteriaBuilder.desc(criteriaBuilder.count(root.get("count_field"))));
    
        return //按计划在订阅者中的计数
    };
}
英文:

Besides pageable interface, spring specifications can also make use of sorting via the criteriaBuilder api as bellow:

public Specification&lt;Plan&gt; hasSort(String sortBy) {
    return (root, query, criteriaBuilder) -&gt; {
    
    query.multiselect(root.get(&quot;fields...&quot;),
                criteriaBuilder.count(root.get(&quot;count_field&quot;)));

    query.orderBy(criteriaBuilder.desc(criteriaBuilder.count(root.get(&quot;count_field&quot;)));
    
     return //count of by Plan in Subscribers
    }
}

huangapple
  • 本文由 发表于 2020年9月15日 13:55:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63895911.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定