美文网首页
SpringBoot入门之CRUD

SpringBoot入门之CRUD

作者: call云飞 | 来源:发表于2017-10-27 09:26 被阅读0次

    前言:

    在大SpringMVC体系中虽然简化了配置,以及类的数量,一个控制器中多个方法可以分别对应不同的业务。但是从根本上来说,需要的配置还是太多,搭建工程重复性的动作还是太多,开发速度还是不够快。还应当,或者说还可以进一步简化,这时SpringBoot横空出世。

    简介:

    SpringBoot 开启了各种自动装配,就是为了简化开发,不需要写各种配置文件,只需要引入相关的依赖就能迅速搭建起一个web工程。

    1. 不需要任何的web.xml配置。
    2. 不需要任何的spring mvc的配置。
    3. 不需要配置tomcat ,springboot内嵌tomcat.
    4. 不需要配置jackson,良好的restful风格支持,自动通过jackson返回json数据
    5. 个性化配置时,最少一个配置文件可以配置所有的个性化信息

    需求简介

    1. 实现关于Student的增删该查
    2. 编码采用restful风格
    3. 数据库使用Map结构代替
    4. 开发工具使用IntelliJ IDEA

    构建工程

    1. 工具准备

    JDK1.8+
    Maven 3.0+
    IDEA 2016+

    2. 创建过程

    create.gif

    3. 引入依赖

    importDependency.gif

    4. pom.xml完整内容

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.springframework</groupId>
        <artifactId>gs-spring-boot</artifactId>
        <version>0.1.0</version>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.8.RELEASE</version>
        </parent>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        </dependencies>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    

    5. 工程目录结构

    -src
      -main
        -java
          -cn
            -itcast
              -springboot
                -dao
                -service
                -entity
                -controller
                -Main.java
        -resouces
               
      -test
    - pom
    

    6. 实体Bean,Student.java编写

    package cn.itcast.springboot.entity;
    
    import java.io.Serializable;
    import java.util.Date;
    
    public class Student implements Serializable{
        private Long id;
        private String name;
        private int age;
        private Date birth;
    
        public Student() {
        }
    
        public Student(Long id, String name, int age, Date birth) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.birth = birth;
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public Date getBirth() {
            return birth;
        }
    
        public void setBirth(Date birth) {
            this.birth = birth;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    ", birth=" + birth +
                    '}';
        }
    }
    

    7. StudentDAO.java接口编写

    package cn.itcast.springboot.dao;
    
    import cn.itcast.springboot.entity.Student;
    
    import java.util.Collection;
    
    public interface StudentDAO {
    
        //获取所有的student
        Collection<Student> getAllStudents();
    
        /**
         * @param id
         * 根据id获取学生
         *
         * @return Student
         * 返回对应的学生对象
         **/
        Student getStudentById(Long id);
    
    
        /**
         * @param student
         * 传入新的student数据
         *
         * @return Collection<Student>
         * 修改成功后返回所有的student
         * */
        Collection<Student> updateStudentById(Student student);
    
    
        /**
         * @param student
         * 传入新的student数据
         *
         * @return Collection<Student>
         * 新增成功后返回所有的student
         * */
        Collection<Student> addStudentById(Student student);
    
    
        /**
         * @param id
         * 传入要删除的student的id
         *
         * @return Collection<Student>
         * 删除成功后返回所有的student
         * */
        Collection<Student> deleteStudentById(Long id);
    }
    

    8. StudentDAOImpl.java 实现类编写

    package cn.itcast.springboot.dao;
    
    import cn.itcast.springboot.entity.Student;
    import org.springframework.stereotype.Repository;
    
    import java.util.Collection;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    
    @Repository("fakeDAO")
    public class StudentDAOImpl implements StudentDAO {
    
        Map<Long,Student> studentMap = new HashMap<Long,Student>(){{
            put(10086L,new Student(10086L,"刘德华",50,new Date()));
            put(10087L,new Student(10087L,"张学友",51,new Date()));
            put(10088L,new Student(10088L,"霍建华",52,new Date()));
            put(10089L,new Student(10089L,"郭富城",53,new Date()));
            put(10090L,new Student(10090L,"陈冠希",54,new Date()));
        }};
    
        @Override
        public Collection<Student> getAllStudents() {
            return studentMap.values();
        }
    
        @Override
        public Student getStudentById(Long id) {
            return studentMap.get(id);
        }
    
        @Override
        public Collection<Student> updateStudentById(Student student) {
            studentMap.put(student.getId(),student);
            return studentMap.values();
        }
    
        @Override
        public Collection<Student> addStudentById(Student student) {
            studentMap.put(student.getId(),student);
            return studentMap.values();
        }
    
        @Override
        public Collection<Student> deleteStudentById(Long id) {
            studentMap.remove(id);
            return studentMap.values();
        }
    }
    

    9. StudentService.java 接口编写

    package cn.itcast.springboot.service;
    
    import cn.itcast.springboot.entity.Student;
    
    import java.util.Collection;
    
    public interface StudentService {
    
        //获取所有的student
        Collection<Student> getAllStudents();
    
        /**
         * @param id
         * 根据id获取学生
         *
         * @return Student
         * 返回对应的学生对象
         **/
        Student getStudentById(Long id);
    
    
        /**
         * @param student
         * 传入新的student数据
         *
         * @return Collection<Student>
         * 修改成功后返回所有的student
         * */
        Collection<Student> updateStudentById(Student student);
    
    
        /**
         * @param student
         * 传入新的student数据
         *
         * @return Collection<Student>
         * 新增成功后返回所有的student
         * */
        Collection<Student> addStudentById(Student student);
    
    
        /**
         * @param id
         * 传入要删除的student的id
         *
         * @return Collection<Student>
         * 删除成功后返回所有的student
         * */
        Collection<Student> deleteStudentById(Long id);
    }
    

    10. StudentServiceImpl.java 实现类编写

    package cn.itcast.springboot.service;
    
    import cn.itcast.springboot.dao.StudentDAO;
    import cn.itcast.springboot.entity.Student;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.Collection;
    
    @Service
    public class StudentServiceImpl implements StudentService {
    
        @Autowired
        private StudentDAO studentDAO;
    
        @Override
        public Collection<Student> getAllStudents() {
            return studentDAO.getAllStudents();
        }
    
        @Override
        public Student getStudentById(Long id) {
            return studentDAO.getStudentById(id);
        }
    
        @Override
        public Collection<Student> updateStudentById(Student student) {
            return studentDAO.updateStudentById(student);
        }
    
        @Override
        public Collection<Student> addStudentById(Student student) {
            return studentDAO.addStudentById(student);
        }
    
        @Override
        public Collection<Student> deleteStudentById(Long id) {
            return studentDAO.deleteStudentById(id);
        }
    }
    

    11. StudentController.java 控制器编写

    package cn.itcast.springboot.controller;
    
    import cn.itcast.springboot.entity.Student;
    import cn.itcast.springboot.service.StudentService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.Collection;
    
    @RestController
    @RequestMapping("students")
    public class StudentController {
       @Autowired
       private StudentService studentService;
    
       @GetMapping
       public Collection<Student> getAllStudents(){
           return studentService.getAllStudents();
       }
    }
    

    12. Main.java 主文件编写

    package cn.itcast.springboot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class Main {
        public static void main(String[] args) {
            SpringApplication.run(Main.class, args);
        }
    }
    

    13. 文件目录

    tree.png

    14. 测试运行

    show.gif

    15. StudentController.java 细节描述

    @RequestMapping("students") //配置全局的访问方式
    @GetMapping //在全局的访问基础上扩充访问,后面不加参数,表示用来匹配全局访问 http://localhost:8080/students,访问方式为GET
    

    16. 重点知识介绍之@RequestMapping

    • RequestMapping的原生用法之常见属性
    • name:指定请求映射的名称,一般省略
    • value:指定请求映射的路径
    • method:指定请求的method类型, 如,GET、POST、PUT、DELETE等;
    • consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
    • produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

    17. 衍生映射:GetMapping,PostMapping,PutMapping,DeleteMapping

    • 这一系列mapping与RequestMapping相类似,可以看作简化版描述
    • 简单比较如:
    1. RequestMapping(method = RequestMethod.GET),含义与GetMapping相同
    2. PostMapping(method = RequestMethod.POST),含义与PostMapping相同
    3. PutMapping与DeleteMapping同上

    18.各种Mapping应用场景综述

    1. 修改数据,PutMapping
    2. 删除数据,DeleteMapping
    3. 查询数据,GetMapping
    4. 新增数据,PostMapping
    5. 总结:通过请求方式来区分业务类别,使得URI变得更简单

    19. 各种Mapping的用法简介

    Mapping类型 URL 解释
    GET www.itcast.cn/students 获取所有的学生信息
    GET www.itcast.cn/students/10086 获取id为10086的学生信息
    POST www.itcast.cn/students 添加学生信息
    PUT www.itcast.cn/students/10086/10086 修改id为10086的学生信息
    DELETE www.itcast.cn/students/10086 删除id为10086的学生信息

    20. 实际Controller,StudentController.java设计

    package cn.itcast.controller;
    
    import cn.itcast.entity.Student;
    import cn.itcast.service.StudentService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.MediaType;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.Collection;
    
    
    @RestController
    @RequestMapping(name = "name", value = "/students",method = RequestMethod.GET)
    public class StudentController {
        @Autowired
        private StudentService studentService;
    
        @GetMapping
        public Collection<Student> getAllStudents() {
    
            return studentService.getAllStudents();
    
        }
    
        @GetMapping(value = "/{id}")
        public Student getStudentById(@PathVariable("id") Long id) {
            return studentService.getStudentById(id);
        }
    
    
        @DeleteMapping(value = "/{id}")
        public Collection<Student> deleteStudentById(@PathVariable("id") Long id) {
            return studentService.deleteStudentById(id);
        }
    
        @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
        public Collection<Student> updateStudentById(@RequestBody Student student) {
            return studentService.updateStudentById(student);
        }
    
        @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
        public Collection<Student> addStudent(@RequestBody Student student) {
            return studentService.addStudent(student);
        }
    }
    

    21. 细节描述

    1. 参数占位声明,{paramNam}:
      @GetMapping(value = "/{id}")
    2. 应用声明参数,@PathVariable("ParamName")
      public Student getStudentById(@PathVariable("id") Long id)
    3. 完整示例
    @GetMapping(value = "/{id}")
        public Student getStudentById(@PathVariable("id") Long id) {
            return studentService.getStudentById(id);
        }
    
    1. 请求参数类型JSON化处理
    @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
        public Collection<Student> updateStudentById(@RequestBody Student student) {
            return studentService.updateStudentById(student);
        }
    

    4.1. 通过consumes属性指定请求参数的提交类型为JSON

    @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    

    4.2. 通过@RequestBody 把请求提交的JSON数据转换为对应的JavaBean

    public Collection<Student> updateStudentById(@RequestBody Student student)
    

    22. 新增学生演示

    addStudent.gif

    23. 修改学生演示

    updateStudent.gif

    24. 删除学生演示

    deleteStudent.gif

    25. 根据id查询学生演示

    queryById.gif

    26. 关于日期类型配置

    1. 用户输入日期值存储到数据库Map中不需要任何配置
    2. 从Map中取出数据时,由于通过jackson封装,所以如果不做特殊配置,会把日期转成从1970-01-01 00:00:00开始到当前时间的毫秒数。
    3. 配置日期的显示格式
      3.1 在resources目录中创建application.properties文件
      3.2 在文件中加入内容
      spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
      spring.jackson.time-zone=GMT+8
      3.3 总览
    overview.png

    3.4 查询测试

    config.gif

    27. 未完待续......下一篇,加入数据库支持

    相关文章

      网友评论

          本文标题:SpringBoot入门之CRUD

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