文章目录
需求分析
- 需求分析
- Control层
- Service
- 开启项目,测试
根据十次方api的分页条件查询如下 可以看到分页条件查询为post请求, 必须传递三个参数. 分别为页码,即当前页. 页大小, 即每页显示条数. 标签的实体类, 为查询条件
在com.tensquare.base.controller.LabelController中写如下的方法 此时service层返回的是Page对象.page对象中含有了总记录数,和每页的内容. 并用了一个PageResult对象进行返回
/**
* 方法名: pageQuery
* 方法描述: 分页条件查询
* 修改日期: 2019/1/9 20:00
* @param label
* @param page
* @param size
* @return entity.Result
* @author taohongchao
* @throws
*/
@RequestMapping(value = "/search/{page}/{size}",method = RequestMethod.POST)
public Result pageQuery(@RequestBody Label label , @PathVariable("page") int page, @PathVariable("size") int size) {
Page pageDate= labelService.pageQuery(label,page,size);
return new Result(true, StatusCode.OK, "查询成功", new PageResult(pageDate.getTotalElements(),pageDate.getContent()));
}
Service
service层返回Page对象. 调用jpa 的findAll的方法, 传递Pageable 参数. 在构造方法中传递page-1,size .page要减一是因为页面传递的是1, 但是从0开始查询的.
public Page pageQuery(Label label, int page, int size) {
Pageable pageAble = new PageRequest(page-1,size);
return labelDao.findAll(new Specification() {
/**
* 方法名: toPredicate
* 方法描述: jpa的条件查询
* 修改日期: 2019/1/7 19:20
* @param root 根对象,要把条件封装到哪个对象中
* @param query 封装查询的关键字. 比如group by order by
* @param cb 封装条件对象 如果直接返回null,表示不封装任何的条件
* @return javax.persistence.criteria.Predicate
* @author taohongchao
* @throws
*/
@Override
public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
//存放一个集合, 用于存储所有的条件
ArrayList list = new ArrayList();
if (label.getLabelname() != null && !"".equals(label.getLabelname())) {
// 根据标签的名称,模糊查询
Predicate predicate = cb.like(root.get("labelname").as(String.class), "%" + label.getLabelname() + "%");
list.add(predicate);
}
if (label.getState() != null && !"".equals(label.getState())) {
//等值查询标签的状态
Predicate predicate = cb.equal(root.get("state").as(String.class), label.getState());
list.add(predicate);
}
//创建一个数组, 作为最终的返回值的条件
Predicate[] parr = new Predicate[list.size()];
//把list转为数组
list.toArray(parr);
//返回所有的条件
return cb.and(parr);
}
},pageAble);
}
开启项目,测试
数据库中的数据如下
传递如下的参数 返回数据如下. 测试成功!
{
"flag": true,
"code": 20000,
"message": "查询成功",
"data": {
"total": 4,
"rows": [
{
"id": "1",
"labelname": "ios",
"state": "1",
"count": 0,
"fans": 0,
"recommend": "1"
},
{
"id": "1081827772546027520",
"labelname": "go",
"state": "1",
"count": 0,
"fans": 0,
"recommend": "1"
},
{
"id": "1081833922754646016",
"labelname": "go",
"state": "1",
"count": 0,
"fans": 0,
"recommend": "1"
},
{
"id": "4",
"labelname": "python",
"state": "1",
"count": null,
"fans": null,
"recommend": null
}
]
}
}