package com.gp.cecp.common.entity;
import java.io.Serializable;
import java.util.Objects;
import java.util.Optional;
import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 基于此对象实现控制层数据的封装,为业务层的返回结果
* 添加状态信息.
*
* @author lidonggui
*/
@Data
@NoArgsConstructor
public class JsonResult implements Serializable {
private static final long serialVersionUID = 5110901796917551720L;
/**
* 状态码:用于标识服务端响应到客户端数据的状态
*/
private long code = 0;//0 正确,1 错误
/**
* 用于记录状态码对象的状态信息
*/
private String msg = "ok";
/**
* 这个属性用于存储业务层返回给控制层的数据或者是控制层自己封装的数据
*/
private Object data;//为什么要用object类型?(业务层返回给控制层数据不知道什么类型)
private long count;
/**
* 当保存,删除,更新更新以后,给出一个消息,可以调用此构造函数封装消息,例如 update Ok
*/
public JsonResult(String message) {
this.msg = message;
}
public JsonResult(IErrorCode errorCode) {
errorCode = (IErrorCode) Optional.ofNullable(errorCode).orElse(ApiErrorCode.FAILED);
this.code = errorCode.getCode();
this.msg = errorCode.getMsg();
}
/**
* 假如希望封装控制层出现的异常信息,可以使用此构造函数
*/
public JsonResult(Throwable e) {
this.code = 1;
this.msg = e.getMessage();
}
public boolean ok() {
return ApiErrorCode.SUCCESS.getCode() == this.code;
}
public JsonResult success(Object data,long count, String msg) {
this.code = 0;
this.msg = msg;
this.data = data;
this.count=count;
return this;
}
public JsonResult fail(Throwable e) {
this.code = 1;
this.msg = e.getMessage();
return this;
}
public long getCode() {
return code;
}
public JsonResult setCode(long code) {
this.code = code;
return this;
}
public String getMsg() {
return msg;
}
public JsonResult setMsg(String msg) {
this.msg = msg;
return this;
}
public Object getData() {
return data;
}
public JsonResult setData(Object data) {
this.data = data;
return this;
}
public long getCount() {
return count;
}
public long setCount(long count) {
this.count = count;
return count;
}
@Override
public String toString() {
return "JsonResult{" +
"code=" + code +
", msg='" + msg + '\'' +
", data=" + data +
", count=" + count +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof JsonResult)) {
return false;
}
JsonResult that = (JsonResult) o;
return getCode() == that.getCode() && Objects.equals(getMsg(), that.getMsg()) && Objects.equals(getData(), that.getData()) && Objects.equals(getCount(), that.getCount());
}
@Override
public int hashCode() {
return Objects.hash(getCode(), getMsg(), getData(), getCount());
}
}