SpringBoot 整合MyBatis 初探
数据库准备
创建 user_info 表:1
2
3
4
5
6CREATE TABLE user_info (
id bigint(20) NOT NULL AUTO_INCREMENT COMMENT '自增主键',
user_id varchar(32) DEFAULT NULL COMMENT '用户标识',
user_name varchar(255) DEFAULT NULL COMMENT '用户姓名',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
初始化数据:1
2INSERT INTO user_info VALUES ('1', '33C21A1821BA43D5AB206AB711750599', '张三');
INSERT INTO user_info VALUES ('2', '5FD890AB3D5F448B9B2BAEF9772EF5AF', '李四');
SpringBoot 工程准备
采用 dependencyManagement
标签方式引入 SpringBoot 依赖,该方式较 parent
标签方式更加灵活。1
2
3
4
5
6
7
8
9
10
11
12<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
添加如下所需依赖:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30<properties>
<mybatis-spring-boot>1.3.1</mybatis-spring-boot>
<mysql-connector>5.1.44</mysql-connector>
</properties>
<dependencies>
<!-- Spring Boot Web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Test 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Boot Mybatis 依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot}</version>
</dependency>
<!-- MySQL 连接驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector}</version>
</dependency>
</dependencies>
配置 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 层
persistence 层包含 Entity 类 及 Mapper 接口。
com.example.persistence.entity 包内定义 UserEntity 类:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41package com.example.persistence.entity;
public class UserEntity {
private Long id;
private String userId;
private String userName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String toString() {
return "UserEnitity{" +
"id=" + id +
", userId='" + userId + '\'' +
", userName='" + userName + '\'' +
'}';
}
}
com.example.persistence.mapper 包内定义 UserMapper 接口:1
2
3
4
5
6
7
8
9package com.example.persistence.mapper;
import com.example.persistence.entity.UserEntity;
public interface UserMapper {
UserEntity getByUserId(String userId);
}
编写 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 层
service 层包含 Service 接口和 Service 实现类。
com.example.service 包内定义 UserService 接口:1
2
3
4
5
6
7
8package com.example.service;
import com.example.persistence.entity.UserEntity;
public interface UserService {
UserEntity getByUserId(String userId);
}
com.example.service.impl 包内定义 UserServiceImpl 实现类:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19package com.example.service.impl;
import com.example.persistence.entity.UserEntity;
import com.example.persistence.mapper.UserMapper;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
public class UserServiceImpl implements UserService {
private UserMapper userMapper;
public UserEntity getByUserId(String userId) {
return userMapper.getByUserId(userId);
}
}
编写 Controller 层
com.example.controller 包内定义 UserController 类:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20package com.example.controller;
import com.example.persistence.entity.UserEntity;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/user/{userId}")
public UserEntity getByUserId(@PathVariable String userId) {
return userService.getByUserId(userId);
}
}
编写 SpringBoot Application 启动类
遵循 SpringBoot Application 默认约定,在 com.example 包根路径定义 Appplication 类:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
"com.example.persistence.mapper"}) (basePackages = {
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class,args);
}
}
@SpringBootApplication 注解是 SpringBoot 基础注解,在此就不详细解释了。
@MapperScan 注解是 Mybatis 和 Spring 整合时的一个注解。 MyBatis 和 Spring 整合时,需要知道 Mapper 接口所在位置,以便运行时生成 Mapper 的代理类。其中 basePackagees 属性用于指定 Mapper 接口所在包路径。支持多个包路径配置,如 basePackages = {“xx”,”xxx”}。其他属性后续遇到再解释。
因为采用默认的自动配置策略,故 @MapperScan 注解标注在 SpringBoot Application 类上,若使用配置类方式自定义配置,也可将该注解标注于配置类上。
运行 UserApplication , 通过浏览器或者 PostMan 等模拟请求工具模拟 GET 请求即可测试接口是否正确返回数据。
本次整合,只是入门级的简单应用,更负杂的场景需要根据相关官方文档进行更多的实践。
具体代码已上传GitHub-lxmuse