SpringBoot中的添加操作
1.userMapper中定义方法
//添加操作(返回的是受影响的行数)
int save(User user);
2.定义一个工具类判断是否为空(其中使用到StringUtil类,需要引入依赖)
public class AssertUtil {
public static void isTrue(Boolean flag,String msg){
if(flag){
throw new ParamException(msg);
}
}
}
3.定义一个ResultInfo类
package org.example.springboot.po.vo;
public class ResultInfo {
private Integer code=200;
private String msg="操作成功";
private Object result;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
}
4.service层
/* 添加用户操作*/
public void saveUser(User user){
AssertUtil.isTrue(StringUtils.isBlank(user.getUserName()),"用户名为空");
AssertUtil.isTrue(StringUtils.isBlank(user.getUserPwd()),"密码为空");
//通过用户名查询对象是否存在
User temp=userMapper.queryUserByUserName(user.getUserName());
AssertUtil.isTrue(null!=temp,"用户已经存在");
AssertUtil.isTrue(userMapper.save(user)<1,"用户添加失败");
}
5.定义一个异常类
public class ParamException extends RuntimeException{
private Integer code=300;
private String msg="参数异常";
public ParamException(){
super("参数异常!");
}
public ParamException(String msg){
super(msg);
this.msg=msg;
}
public ParamException(Integer code){
super("参数异常");
this.code=code;
}
public ParamException(Integer code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
6.controller层
@PutMapping("/user")
public ResultInfo saveUser(User user){
ResultInfo resultInfo=new ResultInfo();
try{
userService.saveUser(user);
}catch(ParamException e){
resultInfo.setCode(e.getCode());
resultInfo.setResult(e.getMsg());
e.printStackTrace();
}catch(Exception e){
resultInfo.setCode(300);
resultInfo.setResult("添加失败");
e.printStackTrace();
}
return resultInfo;
}