整合MyBatis
注意点
- 在相应Mapper接口上通过
@Mapper
注解进行注入;或在程序入口添加@MapperScan(com.hxh.Mapper)
,这其中的所有接口都会被扫描 -
XXXXMapper.xml
存放在resources/MyBatis/mapper
目录下
整合方法
-
配置整合依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency>
-
修改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
-
创建mapper目录以及相应Mapper接口
//@Mapper : 表示本类是一个 MyBatis 的 Mapper @Mapper @Repository public interface DepartmentMapper { // 获取所有部门信息 List<Department> getDepartments(); // 通过id获得部门 Department getDepartment(Integer id); }
-
建立对应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>