SpringBoot数据访问操作

SpringBoot数据访问操作

完成 SpringBoot 与 Mybatis 集成后,接下来以学生表为例实现一套用户模块基本数据维护。

查询操作

接口方法定义

package com.xxxx.springboot.dao;

import com.xxxx.springboot.po.User;

public interface UserDao {
    
    

    //查询操作
    //通过id查询用户对象
    public User queryUserById(Integer id);

}

映射文件配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.xxxx.springboot.dao.UserDao">
    <!--查询操作-->
    <select id="queryUserById" parameterType="int" resultType="com.xxxx.springboot.po.User">
        select * from student where user_id = #{id}
    </select>

</mapper>

UserService

package com.xxxx.springboot.service;

import com.xxxx.springboot.dao.UserDao;
import com.xxxx.springboot.po.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService {
    
    

    @Resource
    private UserDao userDao;

    /**
     * 通过id查询用户对象
     * @param id
     * @return
     */
    public User queryUserById(Integer id){
    
    
        return userDao.queryUserById(id);
    }
}

UserController

package com.xxxx.springboot.controller;

import com.xxxx.springboot.po.User;
import com.xxxx.springboot.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class UserController {
    
    

    @Resource
    private UserService userService;

	/**
     * 查询操作
     * 通过id查询用户对象
     * @param id
     * @return
     */
    @GetMapping("user/id/{id}")
    public User queryUserByName(@PathVariable Integer id){
    
    
        User user = userService.queryUserById(id);
        return user;
    }

}

Postman测试

在这里插入图片描述

添加操作

接口方法定义

package com.xxxx.springboot.dao;

import com.xxxx.springboot.po.User;

public interface UserDao {
    
    

    //添加操作
    public int addUser(User user);
}

映射文件配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.xxxx.springboot.dao.UserDao">

    <!--添加操作-->
    <insert id="addUser" parameterType="com.xxxx.springboot.po.User">
        insert into
            student
            (user_name,user_email,user_age)
        values
            (#{userName},#{userEmail},#{userAge})
    </insert>

</mapper>

添加 commons-lang3 依赖

如果需要使用 StringUtils 工具类,需要引入 commons-lang3 依赖。

  <!-- commons-lang3 -->
  <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
  </dependency>

ParamsException 自定义异常

package com.xxxx.springboot.exception;

/**
 * 自定义异常
 * 参数异常
 */
public class ParamsException extends RuntimeException{
    
    
    private Integer code = 300;
    private String msg = "参数异常!";

    public ParamsException() {
    
    
        super("参数异常!");
    }

    public ParamsException(String msg) {
    
    
        super(msg);
        this.msg = msg;
    }

    public ParamsException(Integer code) {
    
    
        super("参数异常!");
        this.code = code;
    }

    public ParamsException(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;
    }

}

AssertUtil 工具类

package com.xxxx.springboot.utils;

import com.xxxx.springboot.exception.ParamsException;

/**
 * 工具类
 */
public class AssertUtil {
    
    
    /**
     * 判断返回值
     * @param flag
     * @param mag
     */
    public static void isTrue(boolean flag,String mag){
    
    
        //如果为true,则抛出异常
        if(flag){
    
    
            throw new ParamsException(mag);
        }
    }
}

UserService

package com.xxxx.springboot.service;

import com.xxxx.springboot.dao.UserDao;
import com.xxxx.springboot.po.User;
import com.xxxx.springboot.utils.AssertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService {
    
    

    @Resource
    private UserDao userDao;

    /**
     * 添加用户
     * 1.非空校验
     * 2.用户名唯一
     * 3.添加用户记录,判断受影响行数
     * @param user
     */
    public void addUser(User user){
    
    
        //非空校验
        AssertUtil.isTrue(StringUtils.isBlank(user.getUserName()),"用户名不能为空!");
        AssertUtil.isTrue(StringUtils.isBlank(user.getUserEmail()),"用户邮箱不能为空!");
        AssertUtil.isTrue(StringUtils.isBlank(user.getUserAge()),"用户年龄不能为空!");

        //验证用户名的唯一性
        User temp = userDao.queryUserByName(user.getUserName());
        //判断指定用户名查询的用户对象是否存在
        AssertUtil.isTrue(null != temp ,"用户名已存在!");

        //添加用户记录,判断受影响行数
        AssertUtil.isTrue(userDao.addUser(user)<1,"用户添加失败!");

    }

}

ResultInfo

package com.xxxx.springboot.po;

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;
    }
}

UserController

package com.xxxx.springboot.controller;

import com.xxxx.springboot.exception.ParamsException;
import com.xxxx.springboot.po.ResultInfo;
import com.xxxx.springboot.po.User;
import com.xxxx.springboot.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
public class UserController {
    
    

    @Resource
    private UserService userService;


	/**
     * 添加用户
     * @param user
     * @return
     */
    @PostMapping("user/add")
    public ResultInfo addUser(@RequestBody User user){
    
    
        ResultInfo resultInfo = new ResultInfo();
        try{
    
    
            userService.addUser(user);
        }catch (ParamsException p){
    
    
            resultInfo.setCode(p.getCode());
            resultInfo.setMsg(p.getMsg());
            p.printStackTrace();
        }catch (Exception e){
    
    
            e.printStackTrace();
            resultInfo.setCode(500);
            resultInfo.setMsg("用户添加失败");
        }
        return resultInfo;
    }

}

Postman测试

在这里插入图片描述

修改操作

接口方法定义

package com.xxxx.springboot.dao;

import com.xxxx.springboot.po.User;

public interface UserDao {
    
    

    //更新操作
    public int updateUser(User user);
}

映射文件配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.xxxx.springboot.dao.UserDao">

    <!--更新操作-->
    <update id="updateUser" parameterType="com.xxxx.springboot.po.User">
        update
            student
        set
            user_name = #{
    
    userName},
            user_email = #{
    
    userEmail},
            user_age = #{
    
    userAge}
        where
            user_id = #{
    
    userId}
    </update>

</mapper>

UserService

package com.xxxx.springboot.service;

import com.xxxx.springboot.dao.UserDao;
import com.xxxx.springboot.po.User;
import com.xxxx.springboot.utils.AssertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService {
    
    

    @Resource
    private UserDao userDao;

    /**
     * 更新用户
     *
     * @param user
     */
    public void updateUser(User user) {
    
    
        //非空校验
        AssertUtil.isTrue(user.getUserId() == null ,"系统异常,请重试!");
        AssertUtil.isTrue(StringUtils.isBlank(user.getUserName()), "用户名不能为空!");
        AssertUtil.isTrue(StringUtils.isBlank(user.getUserEmail()), "用户邮箱不能为空!");
        AssertUtil.isTrue(StringUtils.isBlank(user.getUserAge()), "用户年龄不能为空!");

        //通过用户名查询用户对象
        User temp = userDao.queryUserByName(user.getUserName());
        //验证用户名唯一性
        AssertUtil.isTrue(null != temp && !(temp.getUserId().equals(user.getUserId())), "用户名已存在!");

        //更新用户记录,判断受影响行数
        AssertUtil.isTrue(userDao.updateUser(user) < 1, "用户记录更新失败!");
    }

}

UserController

package com.xxxx.springboot.controller;

import com.xxxx.springboot.exception.ParamsException;
import com.xxxx.springboot.po.ResultInfo;
import com.xxxx.springboot.po.User;
import com.xxxx.springboot.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
public class UserController {
    
    

    @Resource
    private UserService userService;


    /**
     * 更新用户
     * @param user
     * @return
     */
    @PostMapping("user/update")
    public ResultInfo updateUser(@RequestBody User user){
    
    
        ResultInfo resultInfo = new ResultInfo();
        try{
    
    
            userService.updateUser(user);
        }catch (ParamsException p){
    
    
            resultInfo.setCode(p.getCode());
            resultInfo.setMsg(p.getMsg());
            p.printStackTrace();
        }catch (Exception e){
    
    
            e.printStackTrace();
            resultInfo.setCode(500);
            resultInfo.setMsg("用户更新失败!");
        }
        return resultInfo;
    }

}

Postman测试

在这里插入图片描述

删除操作

接口方法定义

package com.xxxx.springboot.dao;

import com.xxxx.springboot.po.User;

public interface UserDao {
    
    

    //删除操作
    public int deleteUserById(Integer id);
}

映射文件配置

    <!--删除操作-->
    <delete id="deleteUserById" parameterType="int">
        delete from
            student
        where
            user_id = #{userId}
    </delete>

UserService

package com.xxxx.springboot.service;

import com.xxxx.springboot.dao.UserDao;
import com.xxxx.springboot.po.User;
import com.xxxx.springboot.utils.AssertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService {
    
    

    @Resource
    private UserDao userDao;

    /**
     * 删除操作
     * @param id
     */
    public void deleteUserById(Integer id){
    
    
        //判断id是否为空,指定id记录是否存在
        AssertUtil.isTrue(null == id || null == userDao.queryUserById(id),"待删除记录不存在!");
        //执行删除操作,判断受影响行数
        AssertUtil.isTrue(userDao.deleteUserById(id)<1,"用户删除失败!");
    }

}

UserController

package com.xxxx.springboot.controller;

import com.xxxx.springboot.exception.ParamsException;
import com.xxxx.springboot.po.ResultInfo;
import com.xxxx.springboot.po.User;
import com.xxxx.springboot.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
public class UserController {
    
    

    @Resource
    private UserService userService;

    /**
     * 删除用户
     * @param id
     * @return
     */
    @PostMapping("user/delete/{id}")
    public ResultInfo deleteUser(@PathVariable Integer id){
    
    
        ResultInfo resultInfo = new ResultInfo();
        try{
    
    
            userService.deleteUserById(id);
        }catch (ParamsException p){
    
    
            resultInfo.setCode(p.getCode());
            resultInfo.setMsg(p.getMsg());
            p.printStackTrace();
        }catch (Exception e){
    
    
            e.printStackTrace();
            resultInfo.setCode(500);
            resultInfo.setMsg("用户删除失败!");
        }
        return resultInfo;
    }

}

Postman测试

在这里插入图片描述

也可以用相同路径以不同的请求方式去区分不同的操作,比如修改 @PutMapping,删除 @DeleteMapping。

但我不喜欢。

猜你喜欢

转载自blog.csdn.net/lln1540295459/article/details/121376408
今日推荐