概述:
通过简单阅读mybatis源码从本质上了解springboot2.x如何优雅的集成mybatis;
1.引用包
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
2.引用包
在application.poperties中配置
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.password=123456
spring.datasource.username=root
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.connection-timeout=10000
spring.datasource.hikari.maximum-pool-size=10
# 配置mapper.xml,支持classpath*的形式
mybatis.mapper-locations=classpath:com/qlshouyu/framework/demo/mapper/*Mapper.xml
mybatis.type-aliases-package=com.qlshouyu.framework.demo.models
# 驼峰转下划线
mybatis.configuration.map-underscore-to-camel-case=true
3.编写mapper.xml 和 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.qlshouyu.framework.demo.mapper.UserMapper">
<select id="getAll" resultType="com.qlshouyu.framework.demo.models.User">
select * from user
</select>
</mapper>
public interface UserMapper {
List<User> getAll()
}
4.资源打包
在pom.xml的build下面添加以下配置,默认springboot项目不会对xml进行编译到jar包中,这样导致mybatis找不到mapper的xml,所以需要以下配置进行编译打包xml
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
5 指定mapper
有两种方式,两种方式选一个就行了
第一种:是在mappper接口上面用@Mapper注解告诉mybatis 这个接口就是mybaits接口可以生成数据访问代理类;
第二种:在入口applicaion类上面添加注解指定mapper接口所在的包@MapperScan(basePackages = "所在包")
如果想知道为什么这样配置,以及为什么这样优雅的配置请看视频教程视频链接;喜欢点个赞哦