我们首先要把start导入

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>

首先我们要创建pojo,mapper(dao),controller。service层省略

连接数据库

spring:
  datasource:
    username: root
    password: 123456789z
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

在pojo中创建数据库对应字段

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;

}

创建一个mapper接口

@Mapper
@Repository
public interface UserMapper {
    List<User> queryUserList();
    User queryUserById();
    int addUser(User user);
    int updateUser(User user);
    int deleteUser(int id);

}

需要实现接口,使用xml文件,这里我们将mapper文件夹创建在resources文件夹下

为了操作方便需要起别名

spring:
  datasource:
    username: root
    password: 123456789z
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
# 整合mybatis
mybatis:
  type-aliases-package: com.spring03.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml

接下来开始创建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.spring03.mapper.UserMapper">
    <select id="queryUserList" resultType="User">
        select * from user;
    </select>
    <select id="queryUserById" resultType="User">
        select * from user where id = #{id};
    </select>
    <insert id="addUser" parameterType="User">
        insert into user (id,name,pwd) values (#{id},#{name},#{pwd});
    </insert>
    <update id="updateUser" parameterType="User">
        update user set name=#{name},pwd=#{pwd} where id = #{id}
    </update>
    <delete id="deleteUser" parameterType="int">
        delete from user where id = #{id}
    </delete>
</mapper>

写一个controller来测试我们的数据库是否完美连接

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @GetMapping("/all")
    public List<User> queryUserList(){
        List<User> users = userMapper.queryUserList();
        return users;
    }
}

成功打印users;