英文:
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);
但是否有一种方法可以在每个Plan
的Subcriber
数量上使用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<Plan> hasSort(String sortBy) {
return (root, query, criteriaBuilder) -> {
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<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 //count of by Plan in Subscribers
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论