美文网首页springboot
整理基于SpringBoot的RestFul增删改查接口

整理基于SpringBoot的RestFul增删改查接口

作者: YoonaDa | 来源:发表于2018-10-18 16:29 被阅读416次

挺久没有时间整理下最近学的东西了,现在整理下吧,哈哈。下面我来写出代码

1.在数据库上新建一张student_info表
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for student_info
-- ----------------------------
DROP TABLE IF EXISTS `student_info`;
CREATE TABLE `student_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(200) COLLATE utf8_bin DEFAULT NULL,
  `sex` varchar(200) COLLATE utf8_bin DEFAULT NULL,
  `major` varchar(100) COLLATE utf8_bin DEFAULT NULL,
  `height` varchar(100) COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=564458 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
并且插入两条数据吧
INSERT INTO `student_info` VALUES (11, '达达', '男', '软件工程', '178');
INSERT INTO `student_info` VALUES (18, '增删改查', '男', '网络工程', '188');
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
2.运行成功后,student_info表就创建好了
图片.png
3.接下来我们在搭建好的SpringBoot中,各自层下写代码,首先写Entity层吧
package com.yoona.entity;

import lombok.Data;
/**
 * 学生Entity层
 * @author YoonaDa
 * @version 2018-10-17
 * eg.使用lombok省略get,set等方法
 */

@Data
public class Student {

    private int id;
    private String name;
    private String sex;
    private String major;
    private String height;


}

这里,我应用了lombok,@Data用于省略下get、set等方法,大家可以通过在pom.xml中添加以下代码
        <!--添加Lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>
4.StudentMapper.xml的代码
<?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.yoona.dao.StudentDao">
    <!-- 用户结果集 -->
    <!--column后面为数据库对应的值,property后面为entity封装对应的值-->
    <resultMap type="com.yoona.entity.Student" id="studentMap">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="sex" property="sex" />
        <result column="major" property="major" />
        <result column="height" property="height"/>
    </resultMap>
    <!--查询所有数据并以一个List返回json-->
    <select id="findList" resultMap="studentMap" >
        select
        id,
        name,
        sex,
        major,
        height
        from
        student_info
    </select>
<!--通过学生id查询一整天呀-->
    <select id="findStudentById" resultMap="studentMap" parameterType="java.lang.Integer">
        select
        *
        from
        student_info
        where
        id=#{id}
    </select>
    <delete id="delete" parameterType="com.yoona.entity.Student">
      delete from student_info where id=#{id}
    </delete>
<!--以列表的形式添加一条数据-->
    <insert id="insertList" parameterType="com.yoona.entity.Student" useGeneratedKeys="true" keyProperty="id">
        insert into
            student_info(id,name,sex,major,height)
        values
            (#{id},#{name},#{sex},#{major},#{height})
    </insert>
    <!--根据id更新整条数据-->
    <update id="updateList" parameterType="com.yoona.entity.Student">
        update student_info a set
        a.name=#{name},
        a.sex=#{sex},
        a.major=#{major},
        a.height=#{height}
        where a.id=#{id}
    </update>
</mapper>
5.dao层的代码如下
package com.yoona.dao;

import com.yoona.entity.Student;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * 学生Dao层
 * @author YoonaDa
 * @version 2018-10-17
 */
@Mapper
public interface StudentDao {


    List<Student> findStudentById(int id);

    int delete(Student id);

    List<Student> findList(Student student);


    void insertList(Student student);

    void updateList(Student student);
}

6.Service层的代码如下
package com.yoona.service;

import com.yoona.dao.StudentDao;
import com.yoona.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 学生service层
 * @author YoonaDa
 * @version 2018-10-17
 */
@Service
public class StudentService {

    @Autowired
    private StudentDao studentDao;

    public List<Student> findStudentById(int id){

        return studentDao.findStudentById(id);
    }

    //查出所有数据,并以List的形式返回json
    public List<Student> findList(Student student){
        return studentDao.findList(student);
    }

//    根据id删除一整条学生信息
    @Transactional(readOnly = false)
    public void delete(Student student){
        studentDao.delete(student);
    }


    @Transactional(readOnly = false)
    public void insertList(Student student){
        studentDao.insertList(student);
    }

    @Transactional(readOnly = false)
    public void updateList(Student student){
        studentDao.updateList(student);
    }

}

7.controller层代码
package com.yoona.controller;

import com.yoona.common.BaseController;
import com.yoona.common.VResponse;
import com.yoona.entity.Student;
import com.yoona.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 学生Controller
 * @author YoonaDa
 * @version 2018-10-17
 */

@RestController
@RequestMapping(value = "/stu")
public class StudentController extends BaseController {
    @Autowired
    private StudentService studentService;
    /**
     * 用过ID查询信息
     * @param id
     * @return
     *
     * eg.http://localhost:8088/stu/findStudentById?id=5
     */
    @GetMapping("/findStudentById")
    public List<Student> findStudentById(int id){
        return studentService.findStudentById(id);
    }
    /**
     * 以一个List包含起来,返回的json包含在result中,显示为列表
     * @param student
     * @return
     *
     * http://127.0.0.1:8088/stu//findList
     *
     */
    @GetMapping(value = "/findList")
    public VResponse<List<Student>> getList(Student student){
        List<Student> list =studentService.findList(student);
        return VResponse.success(list);
    }
    /**
     * 根据id删除一条数据
     * @param student
     * @return
     */
    @PostMapping(value = "/delete")
    public VResponse<Object> deleteList(Student student){
        studentService.delete(student);
        return VResponse.success("删除成功");
    }
    /**
     * 数据回显,参数id
     * @param student
     * @return
     */
    @RequestMapping(value = "/formList",method = RequestMethod.POST)
         public VResponse<Object> formList(Student student){
         return VResponse.success((Object)student);
         }
    /**
     * 添加一整条数据
     * @param student
     * @param model
     * @return
     *
     * http://localhost:8088/stu/insertList
     */
    @PostMapping(value = "/insertList")
    public VResponse<Object> insertList(Student student,Model model){
        if (!beanValidator(model,student)){
            return formList(student);
        }
        studentService.insertList(student);
        return VResponse.success("增加成功");
    }
    /**
     * 通过id更新一条数据
     * @param student
     * @param model
     * @return
     * http://localhost:8088/stu/updateList
     */
    @PostMapping(value = "/updateList")
    public VResponse<Object> updateList(Student student,Model model){
        if (!beanValidator(model,student)){
            return formList(student);
        }
        studentService.updateList(student);
        return VResponse.success("更新成功");
    }

}

这里我要说明一下,此处我用到我封装在common这个包下的VResponse和beanValidator,并且我这里继承于我封装好的一个BaseController,我写出这里的代码吧,可能没这部分复制进去的小伙伴们controller层会有报错
VResponse
package com.yoona.common;

public class VResponse<T> {
    private int code = 1;
    private String msg = "";
    private T result;

    //通用错误码
    public static final int SUCCESS = 1;

    public VResponse(int errCode, String errMsg) {
        this.code = errCode;
        this.msg = errMsg;
    }

    public VResponse() {

    }

    public static <T> VResponse<T> success(T result){
        VResponse<T> response = new VResponse<T>(SUCCESS, null);
        response.result = result;
        return response;
    }

    public static <T> VResponse<T> success(String msg){
        return new VResponse<T>(SUCCESS, msg);
    }

    public static <T> VResponse<T> success(){
        return new VResponse<T>(SUCCESS, null);
    }

    public static <T> VResponse<T> error(int code,String msg){
        VResponse<T> response = new VResponse<T>();
        response.setCode(code);
        response.setMsg(msg);
        return response;
    }

    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 getResult() {
        return result;
    }

    public void setResult(T result) {
        this.result = result;
    }
}

BaseController
package com.yoona.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import java.util.List;

public abstract class BaseController {

    @Autowired
    protected Validator validator;

    /**
     * 服务端参数有效性验证
     * @param object 验证的实体对象
     * @param groups 验证组
     * @return 验证成功:返回true;严重失败:将错误信息添加到 message 中
     */
    protected boolean beanValidator(Model model, Object object, Class<?>... groups) {
        try{
            BeanValidators.validateWithException(validator, object, groups);
        }catch(ConstraintViolationException ex){
            List<String> list = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
            list.add(0, "数据验证失败:");
            addMessage(model, list.toArray(new String[]{}));
            return false;
        }
        return true;
    }


    /**
     * 添加Model消息
     * @param
     */
    protected void addMessage(Model model, String... messages) {
        StringBuilder sb = new StringBuilder();
        for (String message : messages){
            sb.append(message).append(messages.length>1?"<br/>":"");
        }
        model.addAttribute("message", sb.toString());
    }

}

BeanValidators
package com.yoona.common;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * JSR303 Validator(Hibernate Validator)工具类.
 *
 * ConstraintViolation中包含propertyPath, message 和invalidValue等信息.
 * 提供了各种convert方法,适合不同的i18n需求:
 * 1. List<String>, String内容为message
 * 2. List<String>, String内容为propertyPath + separator + message
 * 3. Map<propertyPath, message>
 *
 * 详情见wiki: https://github.com/springside/springside4/wiki/HibernateValidator
 * @author calvin
 * @version 2013-01-15
 */
public class BeanValidators {

    /**
     * 调用JSR303的validate方法, 验证失败时抛出ConstraintViolationException.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void validateWithException(Validator validator, Object object, Class<?>... groups)
            throws ConstraintViolationException {
        Set constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }

    /**
     * 辅助方法, 转换ConstraintViolationException中的Set<ConstraintViolations>中为List<message>.
     */
    public static List<String> extractMessage(ConstraintViolationException e) {
        return extractMessage(e.getConstraintViolations());
    }

    /**
     * 辅助方法, 转换Set<ConstraintViolation>为List<message>
     */
    @SuppressWarnings("rawtypes")
    public static List<String> extractMessage(Set<? extends ConstraintViolation> constraintViolations) {
        List<String> errorMessages = Lists.newArrayList();
        for (ConstraintViolation violation : constraintViolations) {
            errorMessages.add(violation.getMessage());
        }
        return errorMessages;
    }

    /**
     * 辅助方法, 转换ConstraintViolationException中的Set<ConstraintViolations>为Map<property, message>.
     */
    public static Map<String, String> extractPropertyAndMessage(ConstraintViolationException e) {
        return extractPropertyAndMessage(e.getConstraintViolations());
    }

    /**
     * 辅助方法, 转换Set<ConstraintViolation>为Map<property, message>.
     */
    @SuppressWarnings("rawtypes")
    public static Map<String, String> extractPropertyAndMessage(Set<? extends ConstraintViolation> constraintViolations) {
        Map<String, String> errorMessages = Maps.newHashMap();
        for (ConstraintViolation violation : constraintViolations) {
            errorMessages.put(violation.getPropertyPath().toString(), violation.getMessage());
        }
        return errorMessages;
    }

    /**
     * 辅助方法, 转换ConstraintViolationException中的Set<ConstraintViolations>为List<propertyPath message>.
     */
    public static List<String> extractPropertyAndMessageAsList(ConstraintViolationException e) {
        return extractPropertyAndMessageAsList(e.getConstraintViolations(), " ");
    }

    /**
     * 辅助方法, 转换Set<ConstraintViolations>为List<propertyPath message>.
     */
    @SuppressWarnings("rawtypes")
    public static List<String> extractPropertyAndMessageAsList(Set<? extends ConstraintViolation> constraintViolations) {
        return extractPropertyAndMessageAsList(constraintViolations, " ");
    }

    /**
     * 辅助方法, 转换ConstraintViolationException中的Set<ConstraintViolations>为List<propertyPath +separator+ message>.
     */
    public static List<String> extractPropertyAndMessageAsList(ConstraintViolationException e, String separator) {
        return extractPropertyAndMessageAsList(e.getConstraintViolations(), separator);
    }

    /**
     * 辅助方法, 转换Set<ConstraintViolation>为List<propertyPath +separator+ message>.
     */
    @SuppressWarnings("rawtypes")
    public static List<String> extractPropertyAndMessageAsList(Set<? extends ConstraintViolation> constraintViolations,
                                                               String separator) {
        List<String> errorMessages = Lists.newArrayList();
        for (ConstraintViolation violation : constraintViolations) {
            errorMessages.add(violation.getPropertyPath() + separator + violation.getMessage());
        }
        return errorMessages;
    }
}
这里还要导入几个jar包,在pom.xml中添加如下代码:
        <dependency>
            <groupId>com.google.code.google-collections</groupId>
            <artifactId>google-collect</artifactId>
            <version>snapshot-20080530</version>
        </dependency>
好了,你会发现现在的代码不会有错误了,哈哈哈,对了,附上一张截图吧。
图片.png
8.主程序代码
package com.yoona;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@ComponentScan(basePackages="com.yoona.*")
@SpringBootApplication
@MapperScan("com.yoona.dao")
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
//  解决跨域问题
    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*");
            }
        };
    }

}
9.application.yml
server:
  port: 8088
spring:
  #数据源配置
  datasource:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/test_springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: root123456

mybatis:
  #实体类所在包
  type-aliases-package: com.yoona.entity
  #mapper.xml所在位置
  mapper-locations: classpath:mappings/*.xml
10.运行代码了,哈哈哈
图片.png
11.是时候测试接口了,我们用postman来测试吧
查询所有数据的接口:http://localhost:8088/stu/findList
图片.png
增加一条数据的接口:http://localhost:8088/stu/insertList
图片.png
再一次查询时,我们发现是真的成功插进数据库的表中了
图片.png
测试修改接口吧

http://localhost:8088/stu/updateList

图片.png
再一次查询出来吧,看看更新成功了没
图片.png
更改成功了
测试删除接口:
http://localhost:8088/stu/delete
图片.png
再一次查询,发现真的删除成功了
图片.png
对了,我差点忘记还有一个通过id查询该id信息的接口

http://localhost:8088/stu/findStudentById?id=11

图片.png
成功了!!!
我来附上源码吧
码云源码地址:https://gitee.com/YoonaDa/SpringBoot_Learn.git

相关文章

网友评论

  • 不会写程序的程序猿:挺喜欢看你写的,感觉很清晰、易懂,我也是刚开始用spring boot,在用的过程中也遇到了很多问题,但是没有你那么优秀,你还记录下来,希望有机会可以跟你一起学习和研究,已经关注你的码云了
  • zhuyuansj:确实写的不错.看得出很用心,整理的很完善,加油.
  • 大海_芬:写得不错,继续加油!
  • YoonaDa:小菜鸟升大二了,毕竟自学的东西还有限,还望各位大佬指点指点,我还在努力地自学中:innocent: ,如果觉得写得还可以的话,给我一个赞吧,当成鼓励吧,谢谢大家:blush:

本文标题:整理基于SpringBoot的RestFul增删改查接口

本文链接:https://www.haomeiwen.com/subject/cffszftx.html