04 Spring Boot 整合MyBatis

时间:2022-07-22
本文章向大家介绍04 Spring Boot 整合MyBatis,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

整合MyBatis

注意点

  1. 在相应Mapper接口上通过@Mapper注解进行注入;或在程序入口添加@MapperScan(com.hxh.Mapper),这其中的所有接口都会被扫描
  2. XXXXMapper.xml存放在resources/MyBatis/mapper目录下

整合方法

  1. 配置整合依赖 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency>
  2. 修改yaml配置文件,进行数据库连接配置 spring: datasource: username: root password: 123456 #?serverTimezone=UTC解决时区的报错 url: jdbc:mysql://localhost:3306/db_test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource mybatis: type-aliases-package: com.hxh.pojo
  3. 创建mapper目录以及相应Mapper接口 //@Mapper : 表示本类是一个 MyBatis 的 Mapper @Mapper @Repository public interface DepartmentMapper { // 获取所有部门信息 List<Department> getDepartments(); // 通过id获得部门 Department getDepartment(Integer id); }
  4. 建立对应Mapper映射文件(与接口同名) <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hxh.springboot05mybatis.mapper.BlogTypeMapper"> <select id="blogTypeList" resultType="BlogType"> Select * from t_blogtype </select> <insert id="addBlogType"> insert into t_blogtype values(null, '测试',6); </insert> <update id="updateBlogType" parameterType="BlogType"> update t_blogtype set typeName=#{typeName},orderNo=#{orderNo} where id=#{id} </update> <delete id="delBlogType" parameterType="Integer"> delete from t_blogtype where id=#{id} </delete> </mapper>