首页 > 技术文章 > 阶段5 3.微服务项目【学成在线】_day03 CMS页面管理开发_02-自定义查询页面-服务端-接口开发

wangjunwei 2019-09-22 00:10 原文

在Service中实现自定义查询


StringUtils.isNotEmpty()是这个包下的org.apache.commons.lang3.StringUtils;


再设置其他的条件

定义Example对象

把example作为第一个参数

controller

代码不用改

测试



这里加一个断点测试

可以看到传入的条件

最终查询到的数据

 

最终代码

 

package com.xuecheng.manage_cms.service;

import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.request.QueryPageRequest;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.manage_cms.dao.CmsPageRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

@Service
public class PageService {
    @Autowired
    CmsPageRepository cmsPageRepository;
    public QueryResponseResult findList(int page,int size, QueryPageRequest queryPageRequest) {

        if(queryPageRequest==null){
            queryPageRequest=new QueryPageRequest();
        }
        //自定义查询条件
        ExampleMatcher exampleMatcher=ExampleMatcher.matching()
                .withMatcher("pageAliase",ExampleMatcher.GenericPropertyMatchers.contains());
        //条件之对象
        CmsPage cmsPage=new CmsPage();
        //设置条件值 (站点ID)
        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());
        }
        //定义Exmaple对象
        Example<CmsPage> example=Example.of(cmsPage,exampleMatcher);


        if(page<0){
            page=1;
        }
        page = page -1;
        if(size<=0){
            size = 10;
        }
        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;
    }
}
PageService

 

推荐阅读