歡迎訪問我的GitHub
https://github.com/zq2599/blog_demos
內(nèi)容:所有原創(chuàng)文章分類匯總及配套源碼,涉及Java、Docker强品、Kubernetes扇雕、DevOPS等嚎莉;
本篇概覽
本文是《MyBatis初級實戰(zhàn)》系列的第六篇,繼續(xù)實踐從多表獲取數(shù)據(jù);
-
回顧上一篇照激,咱們實戰(zhàn)了多表關聯(lián)的一對一關系,如下圖所示盹牧,查找日志記錄時俩垃,把對應的用戶信息查出:
在這里插入圖片描述 本篇要實踐的是<font color="blue">一對多關系</font>:查詢用戶記錄時,把該用戶的所有日志記錄都查出來汰寓,邏輯關系如下圖:
在這里插入圖片描述
- 在具體編碼實現(xiàn)一對多查詢時口柳,分別使用聯(lián)表和嵌套兩種方式實現(xiàn),每種方式都按照下圖的步驟執(zhí)行:
在這里插入圖片描述
源碼下載
- 如果您不想編碼有滑,可以在GitHub下載所有源碼跃闹,地址和鏈接信息如下表所示(https://github.com/zq2599/blog_demos):
名稱 | 鏈接 | 備注 |
---|---|---|
項目主頁 | https://github.com/zq2599/blog_demos | 該項目在GitHub上的主頁 |
git倉庫地址(https) | https://github.com/zq2599/blog_demos.git | 該項目源碼的倉庫地址,https協(xié)議 |
git倉庫地址(ssh) | git@github.com:zq2599/blog_demos.git | 該項目源碼的倉庫地址毛好,ssh協(xié)議 |
- 這個git項目中有多個文件夾望艺,本章的應用在<font color="blue">mybatis</font>文件夾下肌访,如下圖紅框所示:
在這里插入圖片描述
- <font color="blue">mybatis</font>是個父工程找默,里面有數(shù)個子工程,本篇的源碼在<font color="blue">relatedoperation</font>子工程中吼驶,如下圖紅框所示:
在這里插入圖片描述
準備數(shù)據(jù)
- 本次實戰(zhàn)惩激,在名為<font color="blue">mybatis</font>的數(shù)據(jù)庫中建立兩個表(和前面幾篇文章中的表結(jié)構一模一樣):user和log表;
- user表記錄用戶信息蟹演,非常簡單风钻,只有三個字段:主鍵、名稱轨帜、年齡
- log表記錄用戶行為魄咕,四個字段:主鍵、用戶id蚌父、行為描述哮兰、行為時間
- user和log的關系如下圖:
在這里插入圖片描述
- 建表和添加數(shù)據(jù)的語句如下:
use mybatis;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL,
`age` int(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `log`;
CREATE TABLE `log` (
`id` int(32) NOT NULL AUTO_INCREMENT,
`user_id` int(32),
`action` varchar(255) NOT NULL,
`create_time` datetime not null,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO mybatis.user (id, name, age) VALUES (3, 'tom', 11);
INSERT INTO mybatis.log (id, user_id, action, create_time) VALUES (3, 3, 'read book', '2020-08-07 08:18:16');
INSERT INTO mybatis.log (id, user_id, action, create_time) VALUES (4, 3, 'go to the cinema', '2020-09-02 20:00:00');
INSERT INTO mybatis.log (id, user_id, action, create_time) VALUES (5, 3, 'have a meal', '2020-10-05 12:03:36');
INSERT INTO mybatis.log (id, user_id, action, create_time) VALUES (6, 3, 'have a sleep', '2020-10-06 13:00:12');
INSERT INTO mybatis.log (id, user_id, action, create_time) VALUES (7, 3, 'write', '2020-10-08 09:21:11');
關于多表關聯(lián)查詢的兩種方式
- 多表關聯(lián)查詢的實現(xiàn)有<font color="blue">聯(lián)表</font>和<font color="blue">嵌套查詢</font>兩種,它們的差異在Mybatis中體現(xiàn)在resultMap的定義上:
- 聯(lián)表時苟弛,resultMap內(nèi)使用<font color="red">collection</font>子節(jié)點喝滞,將聯(lián)表查詢的結(jié)果映射到關聯(lián)對象集合;
- 嵌套時膏秫,resultMap內(nèi)使用<font color="red">association</font>子節(jié)點右遭,association的<font color="red">select</font>屬性觸發(fā)一次新的查詢;
- 上述兩種方式都能成功得到查詢結(jié)果,接下來逐一嘗試窘哈;
聯(lián)表查詢
- 本篇繼續(xù)使用上一篇中創(chuàng)建的子工程<font color="blue">relatedoperation</font>吹榴;
- 實體類<font color="blue">UserWithLogs.java</font>如下,可見成員變量<font color="blue">logs</font>是用來保存該用戶所有日志的集合:
package com.bolingcavalry.relatedoperation.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@ApiModel(description = "用戶實體類(含行為日志集合)")
public class UserWithLogs {
@ApiModelProperty(value = "用戶ID")
private Integer id;
@ApiModelProperty(value = "用戶名", required = true)
private String name;
@ApiModelProperty(value = "用戶地址", required = false)
private Integer age;
@ApiModelProperty(value = "行為日志", required = false)
private List<Log> logs;
}
- 保存SQL的<font color="blue">UserMapper.xml</font>如下滚婉,先把聯(lián)表查詢的SQL寫出來图筹,結(jié)果在名為
<font color="blue">leftJoinResultMap</font>的resultMap中處理:
<?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.bolingcavalry.relatedoperation.mapper.UserMapper">
<select id="leftJoinSel" parameterType="int" resultMap="leftJoinResultMap">
select
u.id as user_id,
u.name as user_name,
u.age as user_age,
l.id as log_id,
l.user_id as log_user_id,
l.action as log_action,
l.create_time as log_create_time
from mybatis.user as u
left join mybatis.log as l
on u.id = l.user_id
where u.id = #{id}
</select>
</mapper>
- <font color="blue">leftJoinResultMap</font>這個resultMap是一對多的關鍵,里面的collection將log的所有記錄映射到<font color="red">logs</font>集合中:
<resultMap id="leftJoinResultMap" type="UserWithLogs">
<id property="id" column="user_id"/>
<result property="name" column="user_name" jdbcType="VARCHAR"/>
<result property="age" column="user_age" jdbcType="INTEGER" />
<collection property="logs" ofType="Log">
<id property="id" column="log_id"/>
<result property="userId" column="log_user_id" jdbcType="INTEGER" />
<result property="action" column="log_action" jdbcType="VARCHAR" />
<result property="createTime" column="log_create_time" jdbcType="TIMESTAMP" />
</collection>
</resultMap>
- 接口定義UserMapper.java :
@Repository
public interface UserMapper {
UserWithLogs leftJoinSel(int id);
}
- service層:
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public UserWithLogs leftJoinSel(int id) {
return userMapper.leftJoinSel(id);
}
}
- controller層的代碼略多让腹,是因為想把swagger信息做得盡量完整:
@RestController
@RequestMapping("/user")
@Api(tags = {"UserController"})
public class UserController {
@Autowired
private UserService userService;
@ApiOperation(value = "根據(jù)ID查找user記錄(包含行為日志)远剩,聯(lián)表查詢", notes="根據(jù)ID查找user記錄(包含行為日志),聯(lián)表查詢")
@ApiImplicitParam(name = "id", value = "用戶ID", paramType = "path", required = true, dataType = "Integer")
@RequestMapping(value = "/leftjoin/{id}", method = RequestMethod.GET)
public UserWithLogs leftJoinSel(@PathVariable int id){
return userService.leftJoinSel(id);
}
}
- 最后是單元測試骇窍,在前文創(chuàng)建的ControllerTest.java中新建內(nèi)部類<font color="blue">User</font>用于user表相關的單元測試瓜晤,可見封裝了一個私有方法queryAndCheck負責請求和驗證結(jié)果,后面的嵌套查詢也會用到:
@Nested
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@DisplayName("用戶服務")
class User {
/**
* 通過用戶ID獲取用戶信息有兩種方式:left join和嵌套查詢腹纳,
* 從客戶端來看痢掠,僅一部分path不同,因此將請求和檢查封裝到一個通用方法中只估,
* 調(diào)用方法只需要指定不同的那一段path
* @param subPath
* @throws Exception
*/
private void queryAndCheck(String subPath) throws Exception {
String queryPath = "/user/" + subPath + "/" + TEST_USER_ID;
log.info("query path [{}]", queryPath);
mvc.perform(MockMvcRequestBuilders.get(queryPath).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(TEST_USER_ID))
.andExpect(jsonPath("$..logs.length()").value(5))
.andDo(print());
}
@Test
@DisplayName("通過用戶ID獲取用戶信息(包含行為日志)志群,聯(lián)表查詢")
@Order(1)
void leftJoinSel() throws Exception {
queryAndCheck(SEARCH_TYPE_LEFT_JOIN);
}
}
- 執(zhí)行上述單元測試方法<font color="blue">leftJoinSel</font>,得到結(jié)果如下:
在這里插入圖片描述
- 為了便于觀察蛔钙,我將上圖紅框中的JSON數(shù)據(jù)做了格式化锌云,如下所示,可見log表中的五條記錄都被關聯(lián)出來了吁脱,作為整個user對象的一個字段:
{
"id": 3,
"name": "tom",
"age": 11,
"logs": [
{
"id": 3,
"userId": 3,
"action": "read book",
"createTime": "2020-08-07"
},
{
"id": 4,
"userId": 3,
"action": "go to the cinema",
"createTime": "2020-09-02"
},
{
"id": 5,
"userId": 3,
"action": "have a meal",
"createTime": "2020-10-05"
},
{
"id": 6,
"userId": 3,
"action": "have a sleep",
"createTime": "2020-10-06"
},
{
"id": 7,
"userId": 3,
"action": "write",
"createTime": "2020-10-08"
}
]
}
- 以上就是通過聯(lián)表的方式獲取一對多關聯(lián)結(jié)果桑涎,接下來咱們嘗試嵌套查詢;
嵌套查詢
- 嵌套查詢的基本思路是將多次查詢將結(jié)果合并兼贡,關鍵點還是在SQL和resultMap的配置上攻冷,先看嵌套查詢的SQL,在<font color="blue">UserMapper.xml</font>文件中遍希,如下等曼,可見僅查詢了user表,并未涉及l(fā)og表:
<select id="nestedSel" parameterType="int" resultMap="nestedResultMap">
select
u.id as user_id,
u.name as user_name,
u.age as user_age
from mybatis.user as u
where u.id = #{id}
</select>
- 上面的SQL顯示結(jié)果保存在名為<font color="blue">nestedResultMap</font>的resultMap中凿蒜,來看這個resultMap禁谦,如下,可見實體類的<font color="blue">logs</font>字段對應的是一個<font color="blue">association</font>節(jié)點废封,該節(jié)點的<font color="blue">select</font>屬性代表這是個子查詢州泊,查詢條件是<font color="red">user_id</font>:
<!-- association節(jié)點的select屬性會觸發(fā)嵌套查詢-->
<resultMap id="nestedResultMap" type="UserWithLogs">
<!-- column屬性中的user_id,來自前面查詢時的"u.id as user_id" -->
<id property="id" column="user_id"/>
<!-- column屬性中的user_name漂洋,來自前面查詢時的"u.name as user_name" -->
<result property="name" column="user_name" jdbcType="VARCHAR"/>
<!-- column屬性中的user_age遥皂,來自前面查詢時的"u.age as user_age" -->
<result property="age" column="user_age" jdbcType="INTEGER" />
<!-- select屬性力喷,表示這里要執(zhí)行嵌套查詢,將user_id傳給嵌套的查詢 -->
<association property="logs" column="user_id" select="selectLogByUserId"></association>
</resultMap>
- 名為selectLogByUserId的SQL和resultMap如下演训,即查詢log表:
<select id="selectLogByUserId" parameterType="int" resultMap="log">
select
l.id,
l.user_id,
l.action,
l.create_time
from mybatis.log as l
where l.user_id = #{user_id}
</select>
<resultMap id="log" type="log">
<id property="id" column="id"/>
<result column="user_id" jdbcType="INTEGER" property="userId"/>
<result column="action" jdbcType="VARCHAR" property="action"/>
<result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
<result column="user_name" jdbcType="VARCHAR" property="userName"/>
</resultMap>
- 以上就是嵌套查詢的關鍵點了弟孟,接下來按部就班的在LogMapper、LogService样悟、LogController中添加方法即可披蕉,下面是LogController中對應的web接口,稍后會在單元測試中調(diào)用這個接口進行驗證:
@ApiOperation(value = "根據(jù)ID查找user記錄(包含行為日志)乌奇,嵌套查詢", notes="根據(jù)ID查找user記錄(包含行為日志),嵌套查詢")
@ApiImplicitParam(name = "id", value = "用戶ID", paramType = "path", required = true, dataType = "Integer")
@RequestMapping(value = "/nested/{id}", method = RequestMethod.GET)
public UserWithLogs nestedSel(@PathVariable int id){
return userService.nestedSel(id);
}
- 單元測試的代碼很簡單眯娱,調(diào)用前面封裝好的queryAndCheck方法即可:
@Test
@DisplayName("通過用戶ID獲取用戶信息(包含行為日志)礁苗,嵌套查詢")
@Order(2)
void nestedSel() throws Exception {
queryAndCheck(SEARCH_TYPE_NESTED);
}
- 執(zhí)行單元測試的結(jié)果如下圖紅框所示,和前面的聯(lián)表查詢一樣:
在這里插入圖片描述
- 兩種方式的一對多關聯(lián)查詢都試過了徙缴,接下來看看兩者的區(qū)別试伙;
聯(lián)表和嵌套的區(qū)別
- 首先是聯(lián)表查詢的日志,如下于样,只有一次查詢:
2020-10-21 20:25:05.754 INFO 15408 --- [ main] c.b.r.controller.ControllerTest : query path [/user/leftjoin/3]
2020-10-21 20:25:09.910 INFO 15408 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
2020-10-21 20:25:09.925 DEBUG 15408 --- [ main] c.b.r.mapper.UserMapper.leftJoinSel : ==> Preparing: select u.id as user_id, u.name as user_name, u.age as user_age, l.id as log_id, l.user_id as log_user_id, l.action as log_action, l.create_time as log_create_time from mybatis.user as u left join mybatis.log as l on u.id = l.user_id where u.id = ?
2020-10-21 20:25:10.066 DEBUG 15408 --- [ main] c.b.r.mapper.UserMapper.leftJoinSel : ==> Parameters: 3(Integer)
2020-10-21 20:25:10.092 DEBUG 15408 --- [ main] c.b.r.mapper.UserMapper.leftJoinSel : <== Total: 5
- 再來看看嵌套查詢的日志疏叨,兩次:
2020-10-21 20:37:29.648 INFO 24384 --- [ main] c.b.r.controller.ControllerTest : query path [/user/nested/3]
2020-10-21 20:37:33.867 INFO 24384 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
2020-10-21 20:37:33.880 DEBUG 24384 --- [ main] c.b.r.mapper.UserMapper.nestedSel : ==> Preparing: select u.id as user_id, u.name as user_name, u.age as user_age from mybatis.user as u where u.id = ?
2020-10-21 20:37:34.018 DEBUG 24384 --- [ main] c.b.r.mapper.UserMapper.nestedSel : ==> Parameters: 3(Integer)
2020-10-21 20:37:34.041 DEBUG 24384 --- [ main] c.b.r.m.UserMapper.selectLogByUserId : ====> Preparing: select l.id, l.user_id, l.action, l.create_time from mybatis.log as l where l.user_id = ?
2020-10-21 20:37:34.043 DEBUG 24384 --- [ main] c.b.r.m.UserMapper.selectLogByUserId : ====> Parameters: 3(Integer)
2020-10-21 20:37:34.046 DEBUG 24384 --- [ main] c.b.r.m.UserMapper.selectLogByUserId : <==== Total: 5
2020-10-21 20:37:34.047 DEBUG 24384 --- [ main] c.b.r.mapper.UserMapper.nestedSel : <== Total: 1
- 至此,MyBatis常用的多表關聯(lián)查詢實戰(zhàn)就完成了穿剖,希望能給您一些參考蚤蔓,接下來的文章,咱們繼續(xù)體驗MyBatis帶給我們的各種特性糊余。
你不孤單秀又,欣宸原創(chuàng)一路相伴
歡迎關注公眾號:程序員欣宸
微信搜索「程序員欣宸」,我是欣宸贬芥,期待與您一同暢游Java世界...
https://github.com/zq2599/blog_demos