Vaz*_*yan 5 spring-data spring-mongo spring-boot spring-mongodb
在 Spring Data JPA 中,我们有规范,并且可以使用规范进行分页和排序。
public interface JpaSpecificationExecutor<T> {
T findOne(Specification<T> var1);
List<T> findAll(Specification<T> var1);
Page<T> findAll(Specification<T> var1, Pageable var2);
List<T> findAll(Specification<T> var1, Sort var2);
long count(Specification<T> var1);
}
Run Code Online (Sandbox Code Playgroud)
但在 MongoRepository 中无法使用此类功能。我尝试使用 QueryByExampleExecutor,但它非常有限 例如我想要过滤年份 >5 和 <20 的数据怎么办?但我想动态生成查询
小智 0
您可以参考下面的代码:
@Repository
public class DataRepository {`enter code here`
@Autowired
MongoTemplate mongoTemplate;
public Page<Data> filterData(SearchDTO searchDTO){
List<Data> list = null;
Integer offset = Optional.ofNullable(searchDTO.getOffset()).orElse(0);
Integer limit = Optional.ofNullable(searchDTO.getLimit()).orElse(10);
int page = offset / limit;
Pageable pageable = PageRequest.of(page, limit);
Query query = new Query();
/** your filter condition */
// if (!StringUtils.isEmpty(searchDTO.getName())) {
// query.addCriteria(Criteria.where("name").is(searchDTO.getName()));
// }
query.with(pageable);
list = mongoTemplate.find(query, Data.class);
return PageableExecutionUtils.getPage(list, pageable,
()-> mongoTemplate.count(query, Data.class));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3073 次 |
| 最近记录: |