IDEA SpringBoot整合Mybatis实现增删改查操作

1.新建一个project

新建项目时选择Spring Initializer

spring boot 实现增删改查 springboot增删改查执行流程_maven

2.创建项目文件结构,选择jdk版本

spring boot 实现增删改查 springboot增删改查执行流程_maven_02

3.选择项目所需要的依赖

首先点击web选择spring web,再点击SQL选择MYSQL,driver等,然后再点击next到新建完成

spring boot 实现增删改查 springboot增删改查执行流程_java_03

4.查看项目新建完成后的pom文件

<?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.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.soyuan</groupId>
    <artifactId>dex-test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>dex-test</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>

        <!--mybatis相关-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </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>

5.修改相关配置文件src/main/resources

5.1将application.properties文件名改为application.yml
5.2在application.yml配置文件,与数据库获取连接.

server:
  port: 8098

spring:
  datasource:
    url: jdbc:mysql://172.26.10.61:3306/dex_wys?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: Password_123

mybatis:
  mapper-locations: classpath:mappers/*.xml
  type-aliases-package: com.suyuan.pojo

#showSql
#logging:
#  level:
logging:
  level:
    com:
      suyuan: debug
#    com.example.demo.mapper: debug

6.该项目的文件结构

在com.suyuan包下分别创建包common,controller,mappers,pojo,service,util.在resources下创建文件夹mappers.具体代码结构如下:

spring boot 实现增删改查 springboot增删改查执行流程_spring boot_04

7.先将一些数据插入到数据库中

  • 7.1在mappers包下创建FlowMapper接口,在接口中写insert方法,来实现数据的插入.
public interface FlowMapper {
    public void insertFlow(Flow flow);
    }

-7.2在pojo包中新建Flow.java,使之与数据库中的字段一一对应

package com.suyuan.pojo;

import org.apache.ibatis.type.Alias;

import java.util.Date;
@Alias("t_flow")
public class Flow {


    private Integer id;
    private String code;
    private String name;
    private Integer type;
    private  Integer log_level;
    private String description;
    private int g_id;
    private  String steps;
    private int status;
    private Date create_time;
    private Date update_time;
    public  Flow(){

    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public Integer getLog_level() {
        return log_level;
    }

    public void setLog_level(Integer log_level) {
        this.log_level = log_level;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getG_id() {
        return g_id;
    }

    public void setG_id(int g_id) {
        this.g_id = g_id;
    }

    public String getSteps() {
        return steps;
    }

    public void setSteps(String steps) {
        this.steps = steps;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Date getCreate_time() {
        return create_time;
    }

    public void setCreate_time(Date create_time) {
        this.create_time = create_time;
    }

    public Date getUpdate_time() {
        return update_time;
    }

    public void setUpdate_time(Date update_time) {
        this.update_time = update_time;
    }

    @Override
    public String toString() {
        return "Flow{" +
                "id=" + id +
                ", code=" + code +
                ", name='" + name + '\'' +
                ", type='" + type + '\'' +
                ", log_level='" + log_level + '\'' +
                ", description='" + description + '\'' +
                ", g_id=" + g_id +
                ", steps=" + steps +
                ", status=" + status +
                ", create_time=" + create_time +
                ", update_time=" + update_time +
                '}';
    }
}
  • 7.3在resources/mappers下创建映射文件FlowMapper.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.suyuan.mappers.FlowMapper">
    <resultMap id="FlowResult" type="com.suyuan.pojo.Flow">
    </resultMap>
    <insert id="insertFlow" parameterType="com.suyuan.pojo.Flow">
        INSERT  INTO
        t_flow(ID,CODE,NAME,TYPE,LOG_LEVEL,DESCRIPTION,G_ID,STEPS,STATUS,CREATE_TIME,UPDATE_TIME)
        VALUES (#{id},#{code},#{name},#{type},#{log_level},#{description},#{g_id},#{steps},#{status},#{create_time},#{update_time})
    </insert>

</mapper>
  • 7.4最后test/java/com/suyuan创建TestApplicationTest 测试类
@SpringBootTest
class TestApplicationTest {

    @Autowired
    private FlowMapper flowMapper;


    @Test
    void contextLoads() {
        Flow flow = new Flow();
        flow.setName("test");
        flow.setCode("aaa");
        flow.setType(1);
        flow.setLog_level(1);
        flow.setDescription("aaa");
        flow.setG_id(1);
        flow.setSteps("aa");
        flow.setStatus(1);
        flow.setCreate_time(new Date());
        flow.setUpdate_time(new Date());
//      flow.setCreate_time(LocalDateTime.now().toString());

        flowMapper.insertFlow(flow);
    }

}

这样就把数据插入数据库中了.

8.完成对数据库中数据的增删改查

  • 8.1在mapper包中对FlowMapper接口里面的方法进行补充
@Mapper
@Repository
public interface FlowMapper {
    public void insertFlow(Flow flow);

    public int insert(Flow flow);
    public int delete(int id);
    public int update(Flow flow);
    //查询所有的数据
    List<Flow> query();
    public Flow FlowInfo(int id);


}
  • 8.2在service包中新建实现类FlowService.java
package com.suyuan.service;



import com.suyuan.mappers.FlowMapper;
import com.suyuan.pojo.Flow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.*;

import java.util.List;

@Service
public class FlowService {
    @Autowired
    private FlowMapper flowMapper;
    //通过id来查询
    public Flow FlowInfo(int id) {

        return flowMapper.FlowInfo(id);
    }
//添加
    public Flow insert(Flow flow) {
       flowMapper.insert(flow);
        return flow;
    };
//删除
    public int delete(int id) {

        return flowMapper.delete(id);
    };
    //修改
    public int update(Flow flow){
        return flowMapper.update(flow);

    };
//查询所有
    public List<Flow> query(){

        return  flowMapper.query();
    };

}
  • 8.3在controller包中新建访问类FlowController.java
package com.suyuan.controller;

import com.suyuan.service.FlowService;
import com.suyuan.pojo.Flow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/resource")
public class FlowController {
@Autowired
   private FlowService flowService;

    @ResponseBody
    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public String index(){

        return "index";
    }
    //通过用户id获取用户所有信息
    @RequestMapping(value = "Flwow/{id}",method = RequestMethod.GET)
    public String GetFlow(@PathVariable int id){

        return flowService.FlowInfo(id).toString();
    }
//通过用户id删除用户
    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    @ResponseBody
    public String delete(int id){
        int result = flowService.delete(id);
        if (result>=1){
            return "删除成功";
        }else {
            return "删除失败";
        }
    }

    //根据用户id更新用户信息
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ResponseBody
    public String update(Flow flow){
        int result=flowService.update(flow);
        if (result>=1){
            return "修改成功";
        }else {
            return "修改失败";

        }
    }
    //插入新用户
    @ResponseBody
    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    public Flow insert(Flow flow){

        return flowService.insert(flow);
    }
    //查询所有用户的信息
    @RequestMapping("/query")
    @ResponseBody
    public List<Flow> ListFlow(){

        return flowService.query();
    }
}
  • 8.4在src/main/resources/mappers文件夹下新建FlowMapper的映射文件UserMapper.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" >
<!--填写对应的dao文件所在的路径-->
<mapper namespace="com.suyuan.mappers.FlowMapper">
  <resultMap id="ResultFlow" type="com.suyuan.pojo.Flow">
              <id property="id" column="id"></id>
              <result property="code" column="code"></result>
              <result property="name" column="name"></result>
              <result property="type" column="type"></result>
              <result property="log_level"  column="log_level"></result>
              <result property="description"  column="description"></result>
              <result property="g_id"  column="g_id"></result>
              <result property="steps"  column="steps"></result>
              <result property="status"  column="status"></result>
              <result property="create_time"  column="create_time"></result>
              <result property="update_time"  column="update_time"></result>
  </resultMap>
    <!--查询用户信息-->
    <select id="getflow" resultType="com.suyuan.pojo.Flow">
        select * from t_flow
        where id=#{id}
    </select>
    <!--删除用户信息-->
    <delete id="delete" parameterType="int">
        delete from t_flow
        where id=#{id}
    </delete>
    <!--返回所有用户信息-->
    <select id="query" resultType="com.suyuan.pojo.Flow">
        select  *
        from t_flow
    </select>
    <!--添加-->
    <insert id="insert" parameterType="com.suyuan.pojo.Flow" keyProperty="id" useGeneratedKeys="true">
    INSERT  INTO
        t_flow(ID,CODE,NAME,TYPE,LOG_LEVEL,DESCRIPTION,G_ID,STEPS,STATUS,CREATE_TIME,UPDATE_TIME)
        VALUES (#{id},#{code},#{name},#{type},#{log_level},#{description},#{g_id},#{steps},#{status},#{create_time},#{update_time})
    </insert>
    <!--根据id更改用户信息-->
    <update id="update" parameterType="com.suyuan.pojo.Flow">

    UPDATE t_flow set t_flow.code=#{code},name=#{name},type=#{type},log_level=#{log_level},
    description=#{description},g_id=#{g_id},steps=#{steps},status=#{status},create_time=#{create_time},update_time=#{update_time}
    where t_flow.id=#{id}
    </update>
</mapper>

-8.5修改程序的启动入口类TestApplication

@SpringBootApplication
@MapperScan(basePackages = " com.suyuan.mappers")
public class TestApplication {

    public static void main(String[] args) {

        SpringApplication.run(TestApplication.class, args);
    }

}

9.验证

到这里就完成了增删改查操作,接下来对上面的代码在Postman中进行验证

  • 9.1通过用户id获取用户信息:
http://localhost:8098/resource/getflow?id=62
  • 9.2通过用户id删除用户
http://localhost:8098/resource/delete?id=62
  • 9.3根据用户id更新用户信息
http://localhost:8098/resource/update?id=45&code=qq&name=qq&type=33&log_level=44&description=wq&g_id=22&steps=rr&status=22
  • 9.4插入新用户
http://localhost:8098/resource/update?code=qq&name=qq&type=33&log_level=44&description=wq&g_id=22&steps=rr&status=22
  • 9.5打印所有用户信息
http://localhost:8098/resource/query