SpringBoot 整合 MyBatis 再探
在上一篇 SpringBoot 整合 MyBatis 初探 中使用@MapperScan注解结合 Mapper.xml 文件 实现 SpringBoot和MyBatis 整合,本次将使用注解方式实现 SpringBoot和MyBaits 整合。
数据库准备
参考 SpringBoot 整合 MyBatis 初探 中的数据库准备
SpringBoot 工程准备
参考 SpringBoot 整合 MyBatis 初探 中的 SpringBoot 工程准备
配置 SpringBoot 配置文件
采用 yml 格式配置文件。yml 格式更有层次感,而且默认编码格式 UTF-8,支持中文参数。
application.yml 内容如下:1
2
3
4
5
6spring:
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.xml 映射文件位置
编写 persistence 层
Entity 可以参考 SpringBoot 整合 MyBatis 初探 中的 UserEntity 类
Mapper 接口存在一些小小的不同:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20package 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 {
@Select("SELECT id, user_id, user_name FROM user_info WHERE user_id = #{userId, jdbcType=VARCHAR}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "userId", column = "user_id"),
@Result(property = "userName", column = "user_name")
})
UserEntity getByUserId(String userId);
}
首先,类上使用 @Mapper 注解,MyBatis 可以自动识别被该注解标准的类,运行时将自动生成代理类
其次,方法上使用 @Select 注解,指定其SQL;使用 @Results 注解,定义其返回映射,等同于ResultMap
因为使用了注解,Mapper.xml 文件可以省略。
编写 Service 层
参考 SpringBoot 整合 MyBatis 初探 中的 编写 Service 层
编写 Controller 层
参考 SpringBoot 整合 MyBatis 初探 中的 编写 Controller 层
编写 SpringBoot Application 启动类
遵循 SpringBoot Application 默认约定,在 com.example 包根路径定义 Appplication 类:1
2
3
4
5
6
7
8
9
10
11
12
13package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class,args);
}
}
仅仅只需要 @SpringBootApplication 注解即可。
运行 UserApplication , 通过浏览器或者 PostMan 等模拟请求工具模拟 GET 请求即可测试接口是否正确返回数据。
本次整合,只是入门级的简单应用,更负杂的场景需要根据相关官方文档进行更多的实践。
具体代码已上传GitHub-lxmuse