美文网首页
4.springboot整合Mybatis进行CRUD

4.springboot整合Mybatis进行CRUD

作者: 王杰磊 | 来源:发表于2019-03-19 10:06 被阅读0次

1.如图建立一个新的模块Spring-boot-demo

image.png

2.在数据库中新建一个库db_spring并新建两张表t_course,t_sys_user并插入数据

t_course.png
t_sys_user.png

3.POM.xml配置(注意版本号不要乱写,可在maven库中查看版本号)

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.Spring.mybatis</groupId>
    <artifactId>spring-boot-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

4.在application.properties文件中配置连接数据库的属性

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.springbootdemo.entity
注意密码和用户名的填写

5.在entity包中建SysUser实体类

package com.spring.mybatis.springbootdemo.entity;

import lombok.Data;

@Data
public class SysUser {
    private Long userId;
    private Long mobile;
    private String password;
    private String username;
    private String avatar;
}

注意数据类型必须用包装类(开头大写)

6.在service包下建立SysUserService接口写数据库增删改查方法,并建一个impl包

package com.spring.mybatis.springbootdemo.service;

import com.spring.mybatis.springbootdemo.entity.SysUser;

import java.util.List;

public interface SysUserService {
    List<SysUser> selectAll();
    SysUser getOne(long userId);
    void delete(long userId);
    SysUser insert(SysUser sysUser);
    void update(SysUser sysUser);
}

7.在impl包下建立SysUserServiceImpl类实现数据库的增删改查方法

package com.spring.mybatis.springbootdemo.service.impl;

import com.spring.mybatis.springbootdemo.entity.SysUser;
import com.spring.mybatis.springbootdemo.mapper.SysUserMapper;
import com.spring.mybatis.springbootdemo.service.SysUserService;
import org.springframework.stereotype.Service;

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

@Service
public class SysUserServiceImpl implements SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public List<SysUser> selectAll() {
        return sysUserMapper.selectAll();
    }

    @Override
    public SysUser getOne(long userId) {
        return sysUserMapper.getOne(userId);
    }

    @Override
    public void delete(long userId) {
        sysUserMapper.delete(userId);
    }

    @Override
    public SysUser insert(SysUser sysUser) {
        sysUserMapper.insert(sysUser);
        return sysUser;
    }

    @Override
    public void update(SysUser sysUser) {
        sysUserMapper.update(sysUser);
    }
}

8.在map包下建SysUserMapper接口,写sql语句和结果集

package com.spring.mybatis.springbootdemo.mapper;

import com.spring.mybatis.springbootdemo.entity.SysUser;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface SysUserMapper {
    @Results({
            @Result(property = "userId",column = "user_id"),
            @Result(property = "mobile",column = "mobile"),
            @Result(property = "password",column = "password"),
            @Result(property = "username",column = "username"),
            @Result(property = "avatar",column = "avatar"),
    })
    @Select("SELECT * FROM t_sys_user ")
    List<SysUser> selectAll();

    @Results({
            @Result(property = "userId",column = "user_id"),
            @Result(property = "mobile",column = "mobile"),
            @Result(property = "password",column = "password"),
            @Result(property = "username",column = "username"),
            @Result(property = "avatar",column = "avatar"),
    })
    @Select("SELECT * FROM t_sys_user WHERE user_id=#{userId} ")
    SysUser getOne(long userId);

    @Delete("DELETE FROM t_sys_user WHERE user_id=#{userId} ")
    void delete(long userId);

    @Insert("INSERT INTO t_sys_user(mobile,password,username,avatar)VALUES(#{mobile},#{password},#{username},#{avatar})")
    void insert(SysUser sysUser);

    @Update("UPDATE t_sys_user SET mobile=#{mobile},password=#{password},username=#{username},avatar=#{avatar}")
    void update(SysUser sysUser);
}

9.测试SysUserServiceImpl方法

package com.spring.mybatis.springbootdemo.service.impl;

import com.spring.mybatis.springbootdemo.entity.SysUser;
import com.spring.mybatis.springbootdemo.service.SysUserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

import java.util.List;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SysUserServiceImplTest {
    @Resource
    private SysUserService sysUserService;
    @Test
    public void selectAll() {
        List<SysUser> userList=sysUserService.selectAll();
        userList.forEach(sysUser -> System.out.println(sysUser));
    }

    @Test
    public void getOne() {
        SysUser sysUser=sysUserService.getOne(2L);
        System.out.println(sysUser);
    }

    @Test
    public void delete() {
        sysUserService.delete(2L);
    }

    @Test
    public void insert() {
        SysUser sysUser=new SysUser();
        sysUser.setMobile((long) 14858258);
        sysUser.setPassword("123wjl");
        sysUser.setUsername("王杰磊");
        sysUser.setAvatar("123.jpg");
        sysUserService.insert(sysUser);
    }

    @Test
    public void update() {
        SysUser sysUser=sysUserService.getOne(2L);
        sysUser.setMobile((long) 1487258);
        sysUser.setPassword("1234wjl");
        sysUser.setUsername("王磊");
        sysUser.setAvatar("13.jpg");
        sysUserService.update(sysUser);
    }
}

注意一定要在SpringBootDemoApplication主类上加上@MapperScan("com.spring.mybatis.springbootdemo.mapper")注解不然会报错
测试结果:


image.png

测试通过

10.在controller包下建SysUserController类

package com.spring.mybatis.springbootdemo.controller;

import com.spring.mybatis.springbootdemo.entity.SysUser;
import com.spring.mybatis.springbootdemo.service.SysUserService;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping(value = "/api")
public class SysUserController {
    @Resource
    private SysUserService sysUserService;

    @RequestMapping(value = "/users",method = RequestMethod.GET)
    public List<SysUser> selectAll(){
        return sysUserService.selectAll();
    }

    @RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
    public SysUser getOne(@PathVariable("id") long id){
        return sysUserService.getOne(id);
    }

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

    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public void addUser(@RequestBody SysUser sysUser){
        sysUserService.insert(sysUser);
    }

    @RequestMapping(value = "/user",method = RequestMethod.PUT)
    public void updateUser(@RequestBody SysUser sysUser){
        sysUserService.update(sysUser);
    }
}

11.用postman测试SysUserController类

注意一定要先运行SpringBootDemoApplication这个主类才能进行测试
测试结果:


image.png
image.png
image.png
image.png
image.png

注意修改put,post,delete,get方法在测试插入,修改方法时要点击下面的body并且手动输入要插入或修改的内容,填修改时一定要把所有字段写全

相关文章

网友评论

      本文标题:4.springboot整合Mybatis进行CRUD

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