SpringData MongoDB的自定义条件查询

本文介绍如何在SpringData JPA中通过自定义接口实现MongoDB的数据查询,特别是使用Example进行条件查询的方法,包括如何设置查询条件、匹配规则及分页处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Dao中定义下面的接口:
spring Data JPA中自定义的相关用法

/**
 * CmsPage:模型类型。
 * Sting:代表的是主键ID的类型。
 * @Description TODO
 * @Author Mr.Wu
 * @Date 2019/7/24 19:23
 * @Version 1.0
 **/
public interface CmsPageRepository extends MongoRepository<CmsPage,String> {

}

service中使用Example进行条件查询

  *
     * @param page :当前页
     * @param size :每页显示的条数
     * @param queryPageRequest :查询条件
     * @return
     */
    public QueryResponseResult findList(int page, int size, QueryPageRequest queryPageRequest){
        if(queryPageRequest==null){
            queryPageRequest = new QueryPageRequest();
        }
        if(page<0){
            page=0;
        }
        if(size<0){
            size =10;
        }
        //自定义条件查询
        //定义条件匹配器
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("pageAliase", ExampleMatcher.GenericPropertyMatchers.contains());

        //条件值对象
        CmsPage cmsPage = new CmsPage();
        //设置条件值
        if(StringUtils.isNotEmpty(queryPageRequest.getSiteId())){
            cmsPage.setSiteId(queryPageRequest.getSiteId());
        }
        //设置模板id作为查询条件
        if(StringUtils.isNotEmpty(queryPageRequest.getTemplateId())){
            cmsPage.setTemplateId(queryPageRequest.getTemplateId());
        }
        //设置页面别名作为查询条件
        if(StringUtils.isNotEmpty(queryPageRequest.getPageAliase())){
            cmsPage.setPageAliase(queryPageRequest.getPageAliase());
        }
        //定义条件对象Example
        Example<CmsPage> example = Example.of(cmsPage,exampleMatcher);


        Pageable pageable= PageRequest.of(page, size);
        Page<CmsPage> all = cmsPageRepository.findAll(example,pageable);  //实现自定义条件查询并且分页查询
        QueryResult queryResult = new QueryResult();
        queryResult.setList(all.getContent());
        queryResult.setTotal(all.getTotalElements());
        QueryResponseResult queryResponseResult = new QueryResponseResult(CommonCode.SUCCESS, queryResult);
        return queryResponseResult;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值