查询过程
1. 查询(简易无入参版)
1.1 数据库查询到返回流程
数据库查询出实体类,在service层对实体类进行调整,返回一个VO类
1.2 类的调整方法
- 常用的类调整方法
- stream 流
- 构造方法
- 反射(通常不用这个,很麻烦哒)
举个栗子: 查询一个VO分页,先查出 entity,再将 entity -> VO 展示到前端
public class example {
public Page<VO> selectPageList(Query query) {
Page<Entity> page = workOperatorDAO.selectPageList(query);
List<Entity> operatorList = page.getRecords();
// entity -> vo,同时用到stream流和构造方法
List<VO> voList = operatorList.stream().map(e -> {
VO vo = new VO(e);
vo.setName(e.getName());
return vo;
}).collect(Collectors.toList());
// 构建分页
Page<VO> voPage = new Page<>();
voPage.setRecords(voList);
voPage.setTotal(page.getTotal());
voPage.setPages(page.getPages());
voPage.setSize(page.getSize());
voPage.setCurrent(page.getCurrent());
return voPage;
}
}
1.3 controller公共响应
- 公共响应体如下
@JsonInclude(JsonInclude.Include.NON_NULL)
public class R<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 成功
*/
private static final int SUCCESS_CODE = Constants.SUCCESS;
/**
* 失败
*/
private static final int FAIL_CODE = Constants.FAIL;
private int code;
private String msg;
private T data;
public static <T> R<T> ok() {
return restResult(null, SUCCESS_CODE, "操作成功");
}
public static <T> R<T> ok(T data) {
return restResult(data, SUCCESS_CODE, null);
}
public static <T> R<T> ok(T data, String msg) {
return restResult(data, SUCCESS_CODE, msg);
}
public static <T> R<T> fail() {
return restResult(null, FAIL_CODE, "操作失败");
}
public static <T> R<T> fail(String msg) {
return restResult(null, FAIL_CODE, msg);
}
public static <T> R<T> fail(T data) {
return restResult(data, FAIL_CODE, null);
}
public static <T> R<T> fail(T data, String msg) {
return restResult(data, FAIL_CODE, msg);
}
public static <T> R<T> fail(int code, String msg) {
return restResult(null, code, msg);
}
public static <T> R<T> fail(T data, int code, String msg) {
return restResult(data, code, msg);
}
private static <T> R<T> restResult(T data, int code, String msg) {
R<T> apiResult = new R<>();
apiResult.setCode(code);
apiResult.setData(data);
apiResult.setMsg(msg);
return apiResult;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public boolean isSuccess() {
return SUCCESS_CODE == code;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE)
.append("code", code)
.append("msg", msg)
.append("data", data)
.toString();
}
}
Constants 是一个final 类,存放公共消息用
1.4 返回的数据
R.ok(Service.method(query));
R.fail();
R.ok();
举个简单栗子:
{"code":200,"data":"新建成功!","success":true}
{
"code": 200,
"data": [
{
"name": "一级",
"value": 1
},
{
"name": "二级",
"value": 2
},
{
"name": "三级",
"value": 3
}
],
"success": true
}