Spring Boot2篇 - 八、Spring Boot 整合Mybatis

八、Spring Boot 整合Mybatis

  • 导入 MyBatis 所需要的依赖
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>
  • 配置数据库连接信息
spring:
  datasource:
    username: root
    password: lian0911
    driver-class-name: com.mysql.jdbc.Driver
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
  • 测试数据库是否连接成功
  • 创建实体类,导入 Lombok
/**
 * @author cVzhanshi
 * @create 2021-06-17 14:39
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class user {
    private Integer id;
    private String username;
    private String password;
}
  • 创建mapper目录以及对应的 Mapper 接口
/**
 * @author cVzhanshi
 * @create 2021-06-17 14:40
 */
//这个注解表示了Mybatis的mapper类
@Mapper
@Repository
public interface UserMapper {
    // 获取所有用户信息
    List<User> getUserForList();

    // 新增一个用户
    int addUser(User user);

    // 通过id获得用户信息
    User getUserById(Integer id);

    // 通过id删除用户
    int deleteById(Integer id);
}

  • 对应的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="cn.cvzhanshi.mapper.UserMapper">

    <select id="getUserForList" resultType="User">
       select * from user
    </select>

    <insert id="addUser" parameterType="User">
        insert into user (username,password)
        values (#{username},#{password});
    </insert>

    <select id="getUserById" resultType="User">
        select * from user where id = #{id}
    </select>
    <delete id="deleteById" parameterType="Integer">
        delete from user where id = #{id}
    </delete>

</mapper>
  • SpringBoot整合MyBatis
#整合mybatis
mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
  type-aliases-package: cn.cvzhanshi.entity

  • 编写用户的 UserController 进行测试
/**
 * @author cVzhanshi
 * @create 2021-06-17 14:53
 */
@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/getUserForList")
    public List<User> getUserForList(){
        List<User> userForList = userMapper.getUserForList();
        return userForList;
    }

    @RequestMapping("/addUser")
    public String addUser(){
        userMapper.addUser(new User(null,"adminadmin","admin"));
        return "add ok";
    }

    @RequestMapping("/getUserById")
    public User getUserById(){
        User userById = userMapper.getUserById(7);
        return userById;
    }

    @RequestMapping("/deleteById")
    public String deleteById(){
        userMapper.deleteById(7);
        return "delete ok";
    }
}

启动项目访问进行测试 ,整合完毕

上一篇:MyBatis入门笔记整理


下一篇:关于 IDEA 中 Mybatis Mapper 自动注入警告的解决方案