SpringBoot 整合 MyBatis 三探
本次将结合前两篇 SpringBoot 整合 MyBatis 初探、SpringBoot 整合 MyBatis 再探 进行整合。
数据库准备
参考 SpringBoot 整合 MyBatis 初探 中的数据库准备
SpringBoot 工程准备
参考 SpringBoot 整合 MyBatis 初探 中的 SpringBoot 工程准备
配置 SpringBoot 配置文件
采用 yml 格式配置文件。yml 格式更有层次感,而且默认编码格式 UTF-8,支持中文参数。
application.yml 内容如下:1
2
3
4
5
6
7
8
9spring:
datasource:
url: jdbc:mysql://192.168.0.110:3306/spring-boot?useSSL=false&useUnicode=true&characterEncoding=utf8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
配置数据源连接信息,以及 MyBatis Mapper.xml 映射文件位置
编写 persistence 层
Entity 可以参考 SpringBoot 整合 MyBatis 初探 中的 UserEntity 类
Mapper 接口存在一些小小的不同:1
2
3
4
5
6
7
8
9
10
11
12
13
14package com.example.persistence.mapper;
import com.example.persistence.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
UserEntity getByUserId(String userId);
}
类上使用 @Mapper 注解,MyBatis 可以自动识别被该注解标准的类,运行时将自动生成代理类
编写 Mapper.xml 文件
Mapper.xml 根据 SpringBoot 配置文件中的设置,约定于 resources/mapper 目录下。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21"1.0" encoding="UTF-8" xml version=
<mapper namespace="com.example.persistence.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.persistence.entity.UserEntity">
<result column="id" property="id" />
<result column="user_id" property="userId" />
<result column="user_name" property="userName" />
</resultMap>
<sql id="Base_Column_List">
id, user_id, user_name
</sql>
<select id="getByUserId" resultMap="BaseResultMap" parameterType="java.lang.String">
SELECT
<include refid="Base_Column_List" />
FROM user_info
WHERE user_id = #{userId, jdbcType=VARCHAR}
</select>
</mapper>
编写 Service 层
参考 SpringBoot 整合 MyBatis 初探 中的 编写 Service 层
编写 Controller 层
参考 SpringBoot 整合 MyBatis 初探 中的 编写 Controller 层
编写 SpringBoot Application 启动类
参考 SpringBoot 整合 MyBatis 再探 Application 类
运行 UserApplication , 通过浏览器或者 PostMan 等模拟请求工具模拟 GET 请求即可测试接口是否正确返回数据。
Mapper 接口通过 @Mapper 注解自动识别,将 SQL 写在 Mapper.xml 文件内,是比较推荐的方法。这也是三探的意义所在。
具体代码已上传GitHub-lxmuse