概述
有时候给前端返回全部数据啊或者单个数据,甚至是对查出的数据进行分页返回都是经常见,有的时候又需要不返回数据,而只返回提示信息就可以了。
分页数据返回一般常见于两个属性,一个是total,分页数,另一个是list,数据列表。
方案
其实在明确了数据情况和需求之后,也就很好设计。
Result类
@Data
public class Result<T> {
private String code;
private String message;
private T data;
public Result(String code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public Result(String code, String message) {
this.code = code;
this.message = message;
}
}
PageResult类:
@Data
@AllArgsConstructor
public class PageResult<T> implements Serializable {
private long total;
private List<T> list;
}
我们来看它们的使用:
返回数据列表:
//findOneById
@RequestMapping("/findOneById")
public Result findOneById(int id){
QueryWrapper<TbBrand> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id",id);
List<TbBrand> tbBrandlist = iTbBrandService.list(queryWrapper);
if (tbBrandlist!=null&&tbBrandlist.size()>0){
return new Result("1","查询成功",tbBrandlist);
}else {
return new Result("2","查询失败");
}
}
分页数据返回:
//分页返回brand对象
@RequestMapping("/findBrandPage")
public Result findBrandPage(@RequestBody TbBrand tbBrand, Integer currentPage, Integer size){
if (currentPage==null||size==null){
return new Result("0","error");
}
QueryWrapper<TbBrand> queryWrapper = new QueryWrapper<>();
queryWrapper.select("first_char","COUNT(*)").groupBy("first_char").having("count(*)>{0}",2);
IPage<TbBrand> iPage = iTbBrandService.page(new Page<>(currentPage,size),queryWrapper);
return new Result("1","good",new PageResult(iPage.getTotal(),iPage.getRecords()));
}
可以看到的一点是,将PageResult看成一个Result中要返回的Data属性,Result不管你怎么来的,以及其中的数据如何设置,我只管返回。即能满足结果信息返回,又能满足分页需求