歡迎訪問(wèn)我的GitHubhttps://github.com/zq2599/blog_demos 內(nèi)容:所有原創(chuàng)文章分類(lèi)匯總及配套源碼,涉及Java、Docker、Kubernetes、DevOPS等; 本篇概覽
源碼下載
準(zhǔn)備數(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'); 關(guān)于多表關(guān)聯(lián)查詢(xún)的兩種方式
聯(lián)表查詢(xún)
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 = "用戶(hù)實(shí)體類(lèi)(含行為日志集合)") public class UserWithLogs { @ApiModelProperty(value = "用戶(hù)ID") private Integer id; @ApiModelProperty(value = "用戶(hù)名", required = true) private String name; @ApiModelProperty(value = "用戶(hù)地址", required = false) private Integer age; @ApiModelProperty(value = "行為日志", required = false) private List<Log> logs; }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "http:///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>
<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>
@Repository public interface UserMapper { UserWithLogs leftJoinSel(int id); }
@Service public class UserService { @Autowired UserMapper userMapper; public UserWithLogs leftJoinSel(int id) { return userMapper.leftJoinSel(id); } }
@RestController @RequestMapping("/user") @Api(tags = {"UserController"}) public class UserController { @Autowired private UserService userService; @ApiOperation(value = "根據(jù)ID查找user記錄(包含行為日志),聯(lián)表查詢(xún)", notes="根據(jù)ID查找user記錄(包含行為日志),聯(lián)表查詢(xún)") @ApiImplicitParam(name = "id", value = "用戶(hù)ID", paramType = "path", required = true, dataType = "Integer") @RequestMapping(value = "/leftjoin/{id}", method = RequestMethod.GET) public UserWithLogs leftJoinSel(@PathVariable int id){ return userService.leftJoinSel(id); } }
@Nested @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @DisplayName("用戶(hù)服務(wù)") class User { /** * 通過(guò)用戶(hù)ID獲取用戶(hù)信息有兩種方式:left join和嵌套查詢(xún), * 從客戶(hù)端來(lái)看,僅一部分path不同,因此將請(qǐng)求和檢查封裝到一個(gè)通用方法中, * 調(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("通過(guò)用戶(hù)ID獲取用戶(hù)信息(包含行為日志),聯(lián)表查詢(xún)") @Order(1) void leftJoinSel() throws Exception { queryAndCheck(SEARCH_TYPE_LEFT_JOIN); } }
{ "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" } ] }
嵌套查詢(xún)
<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>
<!-- association節(jié)點(diǎn)的select屬性會(huì)觸發(fā)嵌套查詢(xún)--> <resultMap id="nestedResultMap" type="UserWithLogs"> <!-- column屬性中的user_id,來(lái)自前面查詢(xún)時(shí)的"u.id as user_id" --> <id property="id" column="user_id"/> <!-- column屬性中的user_name,來(lái)自前面查詢(xún)時(shí)的"u.name as user_name" --> <result property="name" column="user_name" jdbcType="VARCHAR"/> <!-- column屬性中的user_age,來(lái)自前面查詢(xún)時(shí)的"u.age as user_age" --> <result property="age" column="user_age" jdbcType="INTEGER" /> <!-- select屬性,表示這里要執(zhí)行嵌套查詢(xún),將user_id傳給嵌套的查詢(xún) --> <association property="logs" column="user_id" select="selectLogByUserId"></association> </resultMap>
<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>
@ApiOperation(value = "根據(jù)ID查找user記錄(包含行為日志),嵌套查詢(xún)", notes="根據(jù)ID查找user記錄(包含行為日志),嵌套查詢(xún)") @ApiImplicitParam(name = "id", value = "用戶(hù)ID", paramType = "path", required = true, dataType = "Integer") @RequestMapping(value = "/nested/{id}", method = RequestMethod.GET) public UserWithLogs nestedSel(@PathVariable int id){ return userService.nestedSel(id); }
@Test @DisplayName("通過(guò)用戶(hù)ID獲取用戶(hù)信息(包含行為日志),嵌套查詢(xún)") @Order(2) void nestedSel() throws Exception { queryAndCheck(SEARCH_TYPE_NESTED); }
聯(lián)表和嵌套的區(qū)別
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
你不孤單,欣宸原創(chuàng)一路相伴 |
|
來(lái)自: 頭號(hào)碼甲 > 《待分類(lèi)》