SpringBoot整合Mybatis

SpringBoot整合Mybatis

导入mybatis依赖

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>2.1.1</version>
</dependency>

整合测试(yaml方式)

  1. 配置数据库

    spring:
    datasource:
      username: root
      password: 123456
      url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
      driver-class-name: com.mysql.cj.jdbc.Driver
  2. 在配置文件中整合mybatis

    #整合Mybatis
    mybatis:
    type-aliases-package: com.Gao.POJO #别名映射
    mapper-locations: classpath:mybatis/*.xml #.xml文件位置
     #此处若有问题,没有找到.xml则会报错
     #.BindingException: Invalid bound statement (not found):

     

  3. 创建一个实体类POJO(导入lombok来偷懒)

    package com.Gao.POJO;

    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class SysUser {

     private int id;
     private String username;
     private String email;
     private String password;
     private String phoneNum;


    }
  4. 创建Dao层的Mapper

    @Mapper//这个注解就是告诉spring,这是一个mybatis的mapper类, 到Dao层
    @Repository  //Dao层注册到spring容器中
    public interface UserMapper {
       List<SysUser> queryUserList();

       SysUser queryUserById(int id);

       int addUser(SysUser user);

       int updateUser(SysUser user);

       int deleteUser(int id);
    }
  5. 在resources目录下创建mybatis包,创建对应的mapper的映射文件

    <?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.Gao.Mapper.UserMapper">

    <select id="queryUserList" resultType="SysUser">
    select * from sys_user;
    </select>

    <select id="queryUserById" resultType="SysUser">
    select * from system_user where id = #{id};
    </select>

    <insert id="addUser" parameterType="SysUser" >
    insert into sys_user(username,email,password,phoneNum) values (#{username},#{email},#{password},#{phoneNum});
    </insert>

    <update id="updateUser" parameterType="SysUser">
    update sys_user set username = #{username}, email = #{email}, password = #{password}, phoneNum = #{phoneNum} where id = #{id};
    </update>

    <delete id="deleteUser" parameterType="int">
    delete from sys_user where id = #{id};
    </delete>
    </mapper>
  6. 创建一个controller来进行测试

    @RestController
    public class MybatisController {

       @Autowired
       private UserMapper userMapper;

       @GetMapping("/userList")
       public List<SysUser> queryUserList(){
           List<SysUser> userList = userMapper.queryUserList();
           for (SysUser user : userList) {
               System.out.println(user);
          }
           return userList;
      }
    }

    测试结果完成~~

  7.  

posted @ 2021-04-28 16:39  17_Xtreme  阅读(62)  评论(0编辑  收藏  举报