记录:382
场景:在Spring Boot 2.6.3中集成MyBatis 3.5.9操作数据库。实现MyBatis的查、增、改、删操作数据库示例。
MyBatis官网:http://www.mybatis.org/
MyBatis源码:https://github.com/mybatis/
1.初始化准备
1.1创建Maven工程
使用IntelliJ IDEA创建Maven工程。
(1)微服务名称
名称:hub-example-mybatis
(2)微服务groupId和artifactId
groupId: com.hub
artifactId: hub-example-mybatis
(3)微服务核心模块版本
spring-boot 2.6.3
spring-framework 5.3.15
mybatis-spring-boot-starter2.2.2
mybatis-3.5.9
mybatis-spring-2.0.7
HikariCP-4.0.3
1.2准备数据库
本例集成MyBatis,需操作数据库。
创建数据库脚本。
USE mysql;
CREATE DATABASE hub_exampledb DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE USER hub_example@'%' IDENTIFIED BY 'h12345678';
GRANT ALL ON hub_exampledb.* TO 'hub_example'@'%' IDENTIFIED BY 'h12345678';
FLUSH PRIVILEGES;
2.修改pom.xml
修改pom.xml,引入项目依赖Jar、管理Jar包等。
2.1修改pom.xml文件
集成MyBatis,引入核心依赖包。
内容:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
解析:以mybatis-spring-boot-starter方式引入依赖,版本2.2.2,对应mybatis-3.5.9和mybatis-spring-2.0.7。
2.2解析pom.xml文件标签
详情请参考:13.1解析pom.xml文件标签。
3.创建application.yml文件
在application.yml中添加各类配置。
3.1集成MyBatis的配置
(1)基础配置
内容:
mybatis:
mapper-locations: classpath*:mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
解析:mapper-locations属性指定MyBatis映射的SQL文件目录。
注意:属性log-impl在Java类中是logImpl,一般是驼峰命名的大写字母转换小写且在字母前加上短横线。
(2)属性类
MyBatis配置属性主要从以下两个类找到。
类:org.mybatis.spring.boot.autoconfigure.MybatisProperties
类:org.apache.ibatis.session.Configuration
3.2数据源配置
内容:
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/hub_exampledb
username: hub_example
password: h12345678
driver-class-name: com.mysql.cj.jdbc.Driver
解析:配置数据源需求的必备四个属性。
3.3其它基础配置
内容:
server:
servlet:
context-path: /hub-example
port: 18080
spring:
jackson:
time-zone: GMT+8
解析:指定服务器端口和路径前缀。指定时区为东八区。
Jar位置:spring-boot-autoconfigure-2.6.3.jar。
类位置:org.springframework.boot.autoconfigure.web.ServerProperties。
4.创建启动类
包名:com.hub.example。
启动类:HubExampleMybatisApplication。
4.1启动类
(1)内容
@SpringBootApplication
@ComponentScan(basePackages = {"com.hub.example.*"})
@MapperScan(basePackages = "com.hub.example.**.mapper")
public class MybatisExampleApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisExampleApplication.class, args);
}
}
(2)解析
@SpringBootApplication,SpringBoot标记启动类的注解。
@ComponentScan,扫描指定的包,将组件加载到IOC容器中。
@MapperScan,是MyBatis的注解,扫描指定目录下提供给MyBatis注入的接口。
4.2创建包
com.hub.example.domain:微服务使用到的DTO、PO等实体类。
com.hub.example.mapper:MyBatis接口。
com.hub.example.service:服务实现类。
com.hub.example.controller:Controller类,发布Restful接口。
com.hub.example.utils:支撑工具类。
5.编写Java接口(提供给MyBatis使用)
在MyBatis的ORM(Object Relational Mapping)对象映射关系机制中,一个Java接口映射到一个MyBatis的SQL文件,一个接口方法映射到一条MyBatis的SQL语句。
5.1创建Java接口
接口全路径:com.hub.example.mapper.CityMapper
内容:
@Repository
public interface CityMapper {
CityPO queryCityByCityId(String cityId);
List<CityPO> queryCityList(CityPO cityPO);
Integer addCity(CityPO cityPO);
Integer updateCity(CityPO cityPO);
Integer deleteCityById(String cityId);
}
5.2Java接口使用Java实体对象
实体对象全路径:com.hub.example.domain.CityPO
内容:
@Data
public class CityPO implements Serializable {
private Long cityId;
private String cityName;
private Double landArea;
private Long population;
private Double gross;
private String cityDescribe;
private String dataYear;
private Date updateTime;
}
6.编写MyBatis的SQL
一个MyBatis的SQL文件映射到一个Java接口。
一个SQL映射到Java接口的一个方法。
6.1创建MyBatis的SQL文件
(1)文件路径
xml文件全路径:../src/main/resources/mapper/CityMapper.xml
解析:文件路径需被application.yml文件的mybatis的mapperLocations属性扫描到。
(2)文件标准格式
<?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.hub.example.mapper.CityMapper">
..具体SQL..
</mapper>
(3)文件映射关系绑定
文件映射关系绑定:是指Java接口CityMapper和MyBatis的SQL文件CityMapper.xml的关系绑定。
文件映射关系绑定方式:在MyBatis的SQL文件CityMapper.xml的<mapper></mapper>标签的namespace属性namespace="com.hub.example.mapper.CityMapper",指定为Java接口全路径。
文件映射关系绑定生效:在Mybatis运行时会扫描Java接口CityMapper和CityMapper.xml映射文件,建立关系,使用MyBatis的反射机制生成可运行实例。
6.2查询SQL(返回一条记录)
(1)查询语句
<select id="queryCityByCityId" parameterType="String" resultType="com.hub.example.domain.CityPO">
select
CITY_ID AS "cityId",
CITY_NAME AS "cityName",
LAND_AREA AS "landArea",
POPULATION AS "population",
GROSS AS "gross",
CITY_DESCRIBE AS "cityDescribe",
DATA_YEAR AS "dataYear",
UPDATE_TIME AS "updateTime"
from t_city
where CITY_ID = #{cityId}
</select>
(2)接口方法
CityPO queryCityByCityId(String cityId);
(3)解析
<select></select>标签:写查询语句。
id="queryCityByCityId":标签唯一标识,id的值和接口方法名称queryCityByCityId相同,建立一一对应映射关系。
parameterType="String":指定参数类型。
resultType="com.hub.example.domain.CityPO":指定返回值类型。MyBatis会把查询结果封装为CityPO对象。
#{cityId}:#{}传入变量的方式。SQL中的cityId和接口方法入参数cityId是一致的。
封装返回值:t_city表字段CITY_ID的别名cityId,和CityPO的属性cityId是一致,MyBatis自动化封装。
6.3查询SQL(返回多条记录)
(1)查询语句
<select id="queryCityList" parameterType="String" resultType="com.hub.example.domain.CityPO">
select CITY_ID AS "cityId",
CITY_NAME AS "cityName",
LAND_AREA AS "landArea",
POPULATION AS "population",
GROSS AS "gross",
CITY_DESCRIBE AS "cityDescribe",
DATA_YEAR AS "dataYear",
UPDATE_TIME AS "updateTime"
from t_city
<where>
<if test="cityName !=null and cityName!=''">
and CITY_NAME = #{cityName}
</if>
</where>
</select>
(2)接口方法
List<CityPO> queryCityList(CityPO cityPO);
(3)解析
<select></select>标签:写查询语句。
id="queryCityList":标签唯一标识,id的值和接口方法名称queryCityList相同,建立一一对应映射关系。
parameterType="String":指定参数类型。
resultType="com.hub.example.domain.CityPO":指定返回值类型。MyBatis会把查询结果封装为List<CityPO>。
<where></where>标签:MyBatis提供的where条件标签。在标签内使<if>标签可以对入参提供基本条件判断等。
<if></if>标签:条件判断标签。
6.4插入SQL
(1)插入语句
<insert id="addCity">
insert into T_CITY
(CITY_ID,CITY_NAME,LAND_AREA,POPULATION,
GROSS,CITY_DESCRIBE,DATA_YEAR,UPDATE_TIME)
values
(#{cityId},#{cityName},#{landArea},#{population},
#{gross},#{cityDescribe},#{dataYear},#{updateTime})
</insert>
(2)接口方法
Integer addCity(CityPO cityPO);
(3)解析
<insert></insert >标签:写插入语句。
id="addCity":id的值和接口方法名称addCity相同,建立一一对应映射关系。
6.5更新SQL
(1)更新语句
<update id="updateCity">
update
T_CITY
set
LAND_AREA = #{landArea},
POPULATION = #{population},
GROSS = #{gross},
CITY_DESCRIBE = #{cityDescribe},
DATA_YEAR = #{dataYear},
UPDATE_TIME = #{updateTime}
where CITY_ID = #{cityId}
</update>
(2)接口方法
Integer updateCity(CityPO cityPO);
(3)解析
<update></update>标签:写更新语句。
id="updateCity":id的值和接口方法名称updateCity相同,建立一一对应映射关系。
6.6删除SQL
(1)删除语句
<delete id="deleteCityById">
delete
from T_CITY
where CITY_ID = #{cityId}
</delete>
(2)接口方法
Integer updateCity(CityPO cityPO);
(3)解析
<delete></delete>标签:写更新语句。
id="deleteCityById":id的值和接口方法名称deleteCityById相同,建立一一对应映射关系。
7.编写Service层代码
在Service层注入CityMapper接口,以调用接口方式来调用MyBatis机制操作数据库。
7.1Service接口
public interface CityService {
CityDTO queryCityByCityId(String cityId);
List<CityDTO> queryCityList(CityDTO cityDTO);
Integer addCity(CityDTO cityDTO);
Integer updateCity(CityDTO cityDTO);
Integer deleteCityByCityId(String cityId);
}
7.2Service接口实现类
@Service
public class CityServiceImpl implements CityService {
@Autowired
private CityMapper cityMapper;
@Override
public CityDTO queryCityByCityId(String cityId) {
CityPO cityPO = cityMapper.queryCityByCityId(cityId);
return ObjUtils.convertObjectType(cityPO, CityDTO.class);
}
@Override
public List<CityDTO> queryCityList(CityDTO cityDTO) {
CityPO para = ObjUtils.convertObjectType(cityDTO, CityPO.class);
List<CityPO> resultList = cityMapper.queryCityList(para);
List<CityDTO> result2 = Lists.transform(resultList, (entity) -> {
return ObjUtils.convertObjectType(entity, CityDTO.class);
});
return result2;
}
@Override
public Integer addCity(CityDTO cityDTO) {
CityPO para = ObjUtils.convertObjectType(cityDTO, CityPO.class);
return cityMapper.addCity(para);
}
@Override
public Integer updateCity(CityDTO cityDTO) {
CityPO para = ObjUtils.convertObjectType(cityDTO, CityPO.class);
return cityMapper.updateCity(para);
}
@Override
public Integer deleteCityByCityId(String cityId) {
return cityMapper.deleteCityByCityId(cityId);
}
}
8.编写Controller层代码
在Controller层注入Service接口,以调用接口方式来调用Service实现类。
8.1Controller层
@RestController
@RequestMapping("/hub/example/city")
public class CityController {
@Autowired
private CityService cityService;
@PostMapping("/queryCityByCityId")
public ResultObj<CityDTO> queryCityByCityId(String cityId) {
CityDTO cityDTO = cityService.queryCityByCityId(cityId);
return ResultObj.data(200, cityDTO, "执行成功");
}
@PostMapping("/queryCityList")
public ResultObj<List<CityDTO>> queryCityByList(@RequestBody CityDTO cityDTO) {
List<CityDTO> list = cityService.queryCityList(cityDTO);
return ResultObj.data(200, list, "执行成功");
}
@PostMapping("/addCity")
public ResultObj<Integer> addCity(@RequestBody CityDTO cityDTO) {
int result = cityService.addCity(cityDTO);
return ResultObj.data(200, result, "执行成功");
}
@PostMapping("/updateCity")
public ResultObj<Integer> updateCity(@RequestBody CityDTO cityDTO) {
int result = cityService.updateCity(cityDTO);
return ResultObj.data(200, result, "执行成功");
}
@PostMapping("/deleteCityByCityId")
public ResultObj<Integer> deleteCityByCityId(String cityId) {
int result = cityService.deleteCityByCityId(cityId);
return ResultObj.data(200, result, "执行成功");
}
}
9.支撑工具和对象
9.1实体对象
(1)类CityDTO
CityDTO类,封装从前端传入的参数。
@Data
public class CityDTO implements Serializable {
private Long cityId;
private String cityName;
private Double landArea;
private Long population;
private Double gross;
private String cityDescribe;
private String dataYear;
@JsonFormat(
pattern = "yyyy-MM-dd HH:mm:ss"
)
private Date updateTime;
}
(2)类ResultObj
ResultObj类,封装返回前端的结果。
@Data
public class ResultObj<T> implements Serializable {
private int code;
private boolean success;
private String msg;
private T data;
private ResultObj(int code, T data, String msg) {
this.code = code;
this.data = data;
this.msg = msg;
}
public static <T> ResultObj<T> data(int code, T data, String msg) {
return new ResultObj<>(code, data, msg);
}
}
9.2工具类
(1)类ObjUtils
ObjUtils类,把一个对象属性值拷贝到另一个对象属性上。
核心类:org.springframework.cglib.beans.BeanCopier
public class ObjUtils {
public static <T> T convertObjectType(Object obj, Class<T> classz) {
if (obj == null || classz == null) {
return null;
} else {
try {
T result = classz.newInstance();
BeanCopier beanCopier = BeanCopier.create(obj.getClass(), classz, false);
beanCopier.copy(obj, result, (Converter) null);
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
}
10.使用Postman工具测试
使用Postman工具测试。
10.1queryCityByCityId接口
请求路径:http://127.0.0.1:18080/hub-example/hub/example/city/queryCityByCityId
请求方式:POST
入参格式:form-data
入参:cityId=2
10.2queryCityList接口
请求路径:http://127.0.0.1:18080/hub-example/hub/example/city/queryCityList
请求方式:POST
入参格式:JSON
参数:
{
"cityName":"杭州"
}
10.3addCity接口
请求路径:http://127.0.0.1:18080/hub-example/hub/example/city/addCity
请求方式:POST
入参格式:JSON
参数:
{
"cityId": "5",
"cityName": "深圳",
"landArea": "1997.47",
"population": "1768",
"gross": "3.24",
"cityDescribe": "深圳是一个一线城市.",
"dataYear": "2022",
"updateTime": "2023-03-10 19:39:21"
}
10.4updateCity接口
请求路径:http://127.0.0.1:18080/hub-example/hub/example/city/updateCity
请求方式:POST
入参格式:JSON
入参:
{
"cityId": "5",
"cityName": "深圳",
"landArea": "1997.47",
"population": "1768",
"gross": "3.24",
"cityDescribe": "深圳是超级城市.",
"dataYear": "2022",
"updateTime": "2023-03-11 19:39:21"
}
10.5deleteCityById接口
请求路径:http://127.0.0.1:18080/hub-example/hub/example/city/deleteCityByCityId
请求方式:POST
入参格式:form-data
入参:cityId=5
11.建表语句
(1)建表语句
CREATE TABLE t_city (
CITY_ID BIGINT(16) NOT NULL COMMENT '唯一标识',
CITY_NAME VARCHAR(64) COLLATE utf8_bin NOT NULL COMMENT '城市名',
LAND_AREA DOUBLE DEFAULT NULL COMMENT '城市面积',
POPULATION BIGINT(16) DEFAULT NULL COMMENT '城市人口',
GROSS DOUBLE DEFAULT NULL COMMENT '生产总值',
CITY_DESCRIBE VARCHAR(512) COLLATE utf8_bin DEFAULT NULL COMMENT '城市描述',
DATA_YEAR VARCHAR(16) COLLATE utf8_bin DEFAULT NULL COMMENT '数据年份',
UPDATE_TIME DATETIME DEFAULT NULL COMMENT '更新时间'
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='城市信息表';
(2)插入语句
insert into t_city (
CITY_ID,CITY_NAME,LAND_AREA,POPULATION,
GROSS,CITY_DESCRIBE,DATA_YEAR,UPDATE_TIME)
values
('1','杭州','16850','1237','1.81','杭州是一个好城市','2021','2023-03-10 05:39:16'),
('2','杭州','16850','1237','1.88','杭州是一个好城市','2022','2023-03-10 05:39:17'),
('3','苏州','8657.32','1285','2.32','苏州是一个工业城市','2021','2023-03-10 05:39:18'),
('4','苏州','8657.32','1285','2.4','苏州是一个工业城市','2022','2023-03-10 05:39:20');
12.报错
错误信息:Caused by: java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
本例原因:spring-boot-2.6.3和HikariCP-5.0.1版本不匹配。spring-boot-2.6.3默认数据源版本是HikariCP-4.0.3。起初集成时自定义引入了HikariCP-5.0.1,导致启动报错。
解决方式:使用HikariCP-4.0.3版本。
13.附录
13.1解析pom.xml文件标签
在../hub-example-mybatis/pom.xml文件操作。
(1)配置<parent></parent>标签
内容:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
</parent>
功能:指定顶级项目的位置。使用spring-boot作为顶级工程依赖。引用spring-boot下各模块时,无需加版本号。
(2)配置<description></description>标签
内容:
<description>集成mybatis框架应用</description>
功能:描述工程。
(3)配置<packaging></packaging>标签
内容:
<packaging>jar</packaging>
功能:指定打包方式,jar或者war。单模块工程不要使用pom方式打包,可能会加载不到:../src/main/resources下的配置文件。
(4)配置<properties></properties>标签
比如:
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring.boot.maven.plugin.version>2.6.3</spring.boot.maven.plugin.version>
<spring.boot.version>2.6.3</spring.boot.version>
<mybatis-spring-boot-starter.version>2.2.2</mybatis-spring-boot-starter.version>
<mysql-connector-java.version>8.0.30</mysql-connector-java.version>
<lombok.version>1.18.24</lombok.version>
<guava.version>30.1-jre</guava.version>
</properties>
解析:定义的属性值,可以作用在整个pom文件。作用:集中管理Jar包版本等。
(5)配置<dependencyManagement></dependencyManagement>标签
内容:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>${spring.boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
功能:使用dependencyManagement后,会继承dependency列出的项目的默认依赖关系信息。在此处指定版本后,子模块或者dependency标签再引入项目的具体依赖时,不需要加版本号。
(6)配置<dependencies></dependencies>标签
功能:描述与项目关联的所有依赖项。引入具体的<dependency></dependency>标签依赖。
(7)配置<dependency></dependency>标签
比如:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
功能:描述具体依赖。<scope></scope>标签,依赖的范围,属性有:compile、runtime、test、system、provided。其中system属性是以JAR包的形式提供依赖,maven不会在repository查找它。
(8)配置<build></build>
功能:构建项目所需的信息,比如引入构建包的插件以及脚本等。
(9)配置<plugins></plugins>
功能:要使用的插件列表。
(10)配置<plugin></plugin>
功能:具体插件信息。
13.2全量pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hub</groupId>
<artifactId>hub-example-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
</parent>
<description>集成mybatis框架应用</description>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring.boot.maven.plugin.version>2.6.3</spring.boot.maven.plugin.version>
<spring.boot.version>2.6.3</spring.boot.version>
<mybatis-spring-boot-starter.version>2.2.2</mybatis-spring-boot-starter.version>
<mysql-connector-java.version>8.0.30</mysql-connector-java.version>
<lombok.version>1.18.24</lombok.version>
<guava.version>30.1-jre</guava.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>${spring.boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring.boot.maven.plugin.version}</version>
<configuration>
<fork>true</fork>
<addResources>true</addResources>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
以上,感谢。
2023年3月10日