四.Spring Boot 整合 Mybatis 进行CRUD

1.建立好spring-boot-mybatis项目

  • 依赖添加(其他依赖与起步练习项目相同)

            org.projectlombok
            lombok
            1.18.6
            true
        
  • 建立好包 如图


    mybatis包创建.png
  • application.propertirs 数据库连接及制定实体类映射包

若端口号占用可在此处修改
server.port=8080 修改端口号

#server.port=8080   修改端口号
spring.datasource.url=jdbc:mysql://localhost:3306/db_spring?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#指定实体类映射的包
mybatis.type-aliases-package=com.springboot.mybatis.entity

2.代码编写(Course)

  • Course
package com.springboot.mybatis.entity;


import lombok.Data;

@Data
public class Course {
    private Long courseId;
    private String courseName;
    private Long userId;
    private String courseClass;
    private String cover;
    private String courseCode;
    private Short finished;

}

  • CourseMapper
package com.springboot.mybatis.mapper;

import com.springboot.mybatis.entity.Course;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface CourseMapper {



    @Results({@Result(column = "course_id",property = "courseId"),
            @Result(column = "course_name", property = "courseName"),
            @Result(column = "user_id", property = "userId"),
            @Result(column = "course_class", property = "courseClass"),
            @Result(column = "cover", property = "cover"),
            @Result(column = "course_code", property = "courseCode"),
            @Result(column = "finished", property = "finished")
    })
    @Select("SELECT * FROM t_course")
    List selectAll();


    @Results({@Result(column = "course_id",property = "courseId"),
            @Result(column = "course_name", property = "courseName"),
            @Result(column = "user_id", property = "userId"),
            @Result(column = "course_class", property = "courseClass"),
            @Result(column = "cover", property = "cover"),
            @Result(column = "course_code", property = "courseCode"),
            @Result(column = "finished", property = "finished")
    })
    @Select("SELECT * FROM t_course WHERE course_id = #{courseId}")
    Course getOne(Long courseId);


    @Delete( "DELETE FROM  t_course WHERE course_id =#{courseId}" )
    void delete(Long courseId);

    @Insert("INSERT INTO t_course(course_name,user_id,course_class,cover,course_code,finished) " +
            "VALUES(#{courseName},#{userId},#{courseClass},#{cover},#{courseCode},#{finished})")
    void insert(Course course);

    @Update("UPDATE t_course SET cover=#{cover},finished=#{finished} WHERE course_id =#{courseId}")
    void update(Course course);
}

  • CourseService
package com.springboot.mybatis.service;


import com.springboot.mybatis.entity.Course;

import java.util.List;

public interface CourseService {
   List selectAll();

   Course getOne(Long courseId);

   void delete(Long courseId);

   Course insert(Course course);

   void update(Course course);
}

  • CourseServiceImpl
package com.springboot.mybatis.service.impl;

import com.springboot.mybatis.entity.Course;
import com.springboot.mybatis.mapper.CourseMapper;
import com.springboot.mybatis.service.CourseService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
public class CourseServiceImpl implements CourseService {
    @Resource
    private CourseMapper courseMapper;


    @Override
    public List selectAll() {

        return courseMapper.selectAll();
    }

    @Override
    public Course getOne(Long courseId) {

        return courseMapper.getOne(courseId);
    }

    @Override
    public void delete(Long courseId) {

        courseMapper.delete(courseId);
    }

    @Override
    public Course insert(Course course) {
        courseMapper.insert(course);
        return course;
    }

    @Override
    public void update(Course course) {

        courseMapper.update(course);
    }


}

  • 由于班课号是随机数,所以需写一个RandomUtil 方便调用
package com.springboot.mybatis.util;

import java.util.Random;

/*
*
* 随机数工具类
* */
public class RandomUtil {
    public static String getRandomCode(){
        StringBuffer stringBuffer = new StringBuffer();
        Random random = new Random();
        for (int i=0;i<6;i++){
            //生成【0,10】随机整数
            int num = random.nextInt(10);
            //将随机整数加入可变长字符串
            stringBuffer.append(num);
        }

        return stringBuffer.toString();
    }
}

  • 为方便扫包,需要在启动类中加入@MapperScan 如图所示:
@MapperScan("com.springboot.mybatis.mapper")
启动类.png
  • 进行测试!!!(确保测试成功,进行下一步)
package com.springboot.mybatis.service.impl;

import com.springboot.mybatis.entity.Course;
import com.springboot.mybatis.service.CourseService;
import com.springboot.mybatis.util.RandomUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.util.List;
import java.util.RandomAccess;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class CourseServiceImplTest {
    @Resource
    private CourseService courseService;

    @Test
    public void selectAll() {
        List courseList=courseService.selectAll();
        courseList.forEach(course -> System.out.println(course));
    }
    @Test
    public void getOne(){
        Course course=courseService.getOne(4L);
        System.out.println(course);
    }

    @Test
    public void delete(){

        courseService.delete(3L);
    }

    @Test
    public void insert(){
        Course course = new Course();
        course.setCourseName("微信");
        course.setCourseClass("软件1721");
        course.setUserId(2L);
        course.setCover("2.jpg");
        course.setCourseCode(RandomUtil.getRandomCode());
        course.setFinished((short)0);
        courseService.insert(course);
    }

    @Test
    public void update(){
        Course course = courseService.getOne(8L);
        course.setCover("9876543.jpg");
        course.setFinished((short)1);
        courseService.update(course);
    }
}

  • CourseController
package com.springboot.mybatis.controller;

import com.springboot.mybatis.entity.Course;
import com.springboot.mybatis.service.CourseService;
import com.springboot.mybatis.util.RandomUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping(value = "/api")
public class CourseController {
    @Resource
    private CourseService courseService;

   @RequestMapping(value = "/courses",method = RequestMethod.GET)
    public List sectAll(){
       return courseService.selectAll();
   }

   @RequestMapping(value = "/course/{id}",method = RequestMethod.GET)
   public Course getOne(@PathVariable("id") long id){
       return courseService.getOne(id);
   }

    @RequestMapping(value = "/course/{id}",method = RequestMethod.DELETE)
    public void delete(@PathVariable("id") long id){

       courseService.delete(id);
    }

    @RequestMapping(value = "/course",method = RequestMethod.POST)
    public Course addCourse(@RequestBody Course course){
       course.setCourseCode(RandomUtil.getRandomCode());
       return courseService.insert(course);
    }

    /*改*/
    @RequestMapping(value = "/course", method = RequestMethod.PUT)
    public void updateCourse(@RequestBody Course course) {
        courseService.update(course);
    }

}

  • Postman 运行测试(200表示操作成功)


    全查.png

    单查.png

    删.png

    增.png

    改.png

3.user 类

上传至GitHub

你可能感兴趣的:(四.Spring Boot 整合 Mybatis 进行CRUD)