|
|
3 o- H' X5 |5 O% a( p0 O+ j1 S! }
<h3 id="一序言">一、序言</h3>* k( I, L/ `0 b3 y2 A8 h1 }
<h4 id="一背景内容">(一)背景内容</h4>0 \1 I7 \. g$ a
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>: h$ R3 h+ d, d) a+ g1 d; |& Y
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>% @+ N( A# \7 i$ K" W
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>8 r) u$ f2 s) [* J9 e* h7 u2 p
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>2 }* ~* v1 w# C" J
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
# W2 r+ p0 b! R6 j b" c<h4 id="二场景说明">(二)场景说明</h4>
& M4 |( U! e1 y. T8 G* [' ]<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p># E1 v2 B+ F6 S+ ?/ g* q9 V* e
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >; x, O8 k0 J5 R6 L
<h4 id="三前期准备">(三)前期准备</h4>
6 x; Z7 ]; D4 Y: [' a% o<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>/ i7 g& R' O% n
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
- B) u7 G% B: i; J- ~! a<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
5 c% n O: |+ L& [ J! N! k: |<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
. q1 l1 b4 F" v<h3 id="二一对一查询">二、一对一查询</h3>+ u$ @+ ?- u" _8 E
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>% [# E6 [/ e7 U) \/ t7 T4 `4 n
<h4 id="一查询单条记录">(一)查询单条记录</h4>
! I: y. |; f/ R0 a& \ ^<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
* G1 L" V' E; p' U( _5 W<h5 id="1示例代码">1、示例代码</h5> ?3 G5 A7 X j/ F* d# s2 @
<pre><code class="language-java">/**, X, [2 N5 u6 \4 A4 |6 t
* 查询单个学生信息(一个学生对应一个部门) ]) G& z& c$ b" U( f- t$ A
*/. D& L* F6 B; z& V1 S( Q
public UserVo getOneUser(Integer userId) {* H" L/ @, B$ x$ U
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class)+ y' a' o. M! M0 N! e
.eq(User::getUserId, userId);
# f7 L( V( d6 |% ?5 e7 ` // 先查询用户信息
& Z6 N3 y: [# G7 Y4 r, Y. S+ F User user = userMapper.selectOne(wrapper);
; [; W4 Q" D0 I$ C3 Q. n' O // 转化为Vo# J3 ~4 U2 d+ h5 }! g
UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);2 u8 O& W4 Y! R: O
// 从其它表查询信息再封装到Vo
# L, x$ m3 T0 D' v& S2 x Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
5 b0 p# F5 m( W- t& V x return userVo;
2 f' d! ~( N Q9 A* Y* H}9 @& _$ {8 f* H/ M
</code></pre>
2 H& k$ w0 G. k<p>附属表信息补充</p>
_ _9 |8 x% U3 a* g% t<pre><code class="language-java">/*** [; C9 O% c4 ]: X( u$ B' T; T
* 补充部门名称信息9 ^* _3 p, Q1 D# I) x- r& a% N
*/
8 r' W; c9 N5 {( ]3 W1 vprivate void addDetpNameInfo(UserVo userVo) {/ U- k. Z; U) m, E- W
LambdaQueryWrapper<Dept> wrapper = Wrappers.lambdaQuery(Dept.class), @) s s# T: ~1 f# o0 ?6 k
.eq(Dept::getDeptId, userVo.getDeptId());- M8 L$ q& V& R, Z$ A' [% m/ z' E
Dept dept = deptMapper.selectOne(wrapper);$ Y9 Q+ J( ^7 f" O9 D* m5 I6 _
Optional.ofNullable(dept).ifPresent(e -> userVo.setDeptName(e.getDeptName()));
3 d" u4 J, Y& p5 \}2 H$ u( p. i% H/ Q! h
</code></pre>
1 K& J5 w1 U+ {<h5 id="2理论分析">2、理论分析</h5>( d/ Y4 P* m- k3 l2 i1 d7 `! W
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
& X3 ?+ @0 e& C$ z% s<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>3 ^. X6 [2 A8 }9 g e5 N- c
<h4 id="二查询多条记录">(二)查询多条记录</h4>
5 p+ D! H+ P F7 X7 C/ X<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
( a+ _: Z# F: X/ c<h5 id="1示例代码-1">1、示例代码</h5>
0 b% P2 Y- d3 c5 G" N<pre><code class="language-java">/**
; ?. [; w! `3 Y+ n * 批量查询学生信息(一个学生对应一个部门)
7 O4 o: {8 R3 f& O. T */
: N. r+ O' v+ H3 a! H- p8 ^; ypublic List<UserVo> getUserByList() {
, D) M3 r4 ~6 @& g+ n8 b& n6 @ // 先查询用户信息(表现形式为列表)" y( N' u8 t* s# T9 S: g" ?1 k6 c: K
List<User> user = userMapper.selectList(Wrappers.emptyWrapper());
& k5 {! V2 j& ~, O0 A9 F" u0 u List<UserVo> userVos = user.stream().map(UserVo::new).collect(toList());
/ @, U9 z& _# p. `$ Y // 此步骤可以有多个+ [. J S' t4 P8 b* g: `2 L- G6 k3 C" E
addDeptNameInfo(userVos);
' r0 b& P4 g, U s% g return userVos;
2 n, o# M8 O. P. @, I( k4 y9 Y}( ?9 o: [' Q w2 L
</code></pre>
/ l6 h: u" L+ b, w: ]<p>附属信息补充</p>8 [% K+ O, S# v. S& d4 h
<pre><code class="language-java">private void addDeptNameInfo(List<UserVo> userVos) {
! r+ c/ g4 _% S // 提取用户userId,方便批量查询; k5 a8 O- r% ]4 F4 u: |6 W
Set<Integer> deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
" u) a; i/ F' H( Z0 `5 d6 w // 根据deptId查询deptName(查询前,先做非空判断)7 L( _4 x9 l* t+ V! g
List<Dept> dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));0 w+ F7 l1 Z& I
// 构造映射关系,方便匹配deptId与deptName
& L n5 a% P/ l" N) ? Map<Integer, String> hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));. Q+ l- f3 c! v, ^! O% j0 ~
// 封装Vo,并添加到集合中(关键内容)' y$ _; \0 p. K/ ^# D1 J& i+ {
userVos.forEach(e -> e.setDeptName(hashMap.get(e.getDeptId())));
# [ n1 N9 c) w7 h1 {5 u( M}
; Z# O$ p, l3 A% f</code></pre>
* P, L j) w) L! ]) V- K' s<h5 id="2理论分析-1">2、理论分析</h5>
5 _5 Z9 u b) o! B<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>% S W7 J" O1 K+ N1 y
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
5 U6 _/ y: U; `4 U( M$ w% C L<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>4 }$ z( J) K$ m5 A+ V r
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
' v( c! F8 y- Z<h5 id="1示例代码-2">1、示例代码</h5>
1 V; Z) w! v$ Y' \5 n<pre><code class="language-java">/**
/ z& z2 x8 c- U; |5 b7 J5 ^- B8 U * 分页查询学生信息(一个学生对应一个部门)
7 D: \( w+ f/ X# }, N */
( o% v& D+ Z% m {) L# xpublic IPage<UserVo> getUserByPage(Page<User> page) {
1 L, M: }: _. k( N8 }: ?8 r // 先查询用户信息
* e8 v- H! X. S/ G% D# w* h IPage<User> xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
; t* z* e6 D6 I" x1 Y& ` // 初始化Vo
6 {5 n9 W2 E5 Q* V6 n IPage<UserVo> userVoPage = xUserPage.convert(UserVo::new);
4 O* {1 U) ]6 V- J, d( r9 \ if (userVoPage.getRecords().size() > 0) {
; A/ w1 v- g# g* a. I$ m" F2 Y+ a! n addDeptNameInfo(userVoPage);- f% c Q# O7 \8 W6 w, @
}
- q, V5 z, s. n* N0 N) p return userVoPage;
- Z1 j( l( n |/ ~}) s/ I3 w& \& M8 p5 T
</code></pre>1 a$ E* N7 C1 z" W7 x C2 I
<p>查询补充信息</p>* ~6 N/ S# B- u2 @. A/ |1 c
<pre><code class="language-java">private void addDeptNameInfo(IPage<UserVo> userVoPage) {& J0 `2 \8 W3 L/ }0 M
// 提取用户userId,方便批量查询
( i, W' }7 } u Set<Integer> deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());' Y, b) k6 {9 J% K4 h6 f" Y
// 根据deptId查询deptName/ T8 @ ~! c. ?
List<Dept> dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
+ w2 z9 K# q. T% Z' V# c- ^ // 构造映射关系,方便匹配deptId与deptName! C2 v3 x0 j0 S; g. r: m3 Y
Map<Integer, String> hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
8 @- A( z6 J+ Y8 T# w // 将查询补充的信息添加到Vo中9 f" M% B q$ S& H6 U$ }3 ~
userVoPage.convert(e -> e.setDeptName(hashMap.get(e.getDeptId())));
5 b+ z7 L1 z5 U/ h6 ]}
3 @9 e. t" q8 Y' d' D: Y+ n& J</code></pre>% S3 U0 G! R2 J+ a. p5 x Z
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>' M' \! w& q) n$ C
<h5 id="2理论分析-2">2、理论分析</h5>- S; P, G( P9 k9 D
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
H, q) g; N6 {. o! T F9 I<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
" t' T3 p/ U5 |; L. s2 |$ z. K<h3 id="三一对多查询">三、一对多查询</h3>* | U, u! w U( x- x/ ~4 k: O, Y
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>7 F( A! A$ u: T0 L
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
0 J5 k* P6 ]6 y* n' i" t<h5 id="1示例代码-3">1、示例代码</h5>6 {1 t( a. _; \1 T* i
<pre><code class="language-java">/**
8 c M- [* }, t) I+ a6 M# \ * 查询单个部门(其中一个部门有多个用户)
7 u1 ?7 A' u- n */$ x* [) \7 r- P9 D* M- }$ [
public DeptVo getOneDept(Integer deptId) {
6 v; f' A: [1 F% I& ? // 查询部门基础信息
. ]( w4 ?2 J. Q3 ]; J( b7 F LambdaQueryWrapper<Dept> wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);: r/ P6 W. B v; ^5 x6 {
DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
5 s; s( H) p8 w* { j0 P Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);" L, b; a& I+ q/ h3 {8 }/ H
return deptVo;8 p9 S1 g; R- K3 g: h8 v1 }
}
& a, L& j7 d) |</code></pre>
& M3 a% z: V6 j! k<p>补充附加信息</p>
: B5 F( `5 n) C6 P& x8 t( z5 a<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {1 _! Z! A% X7 q
// 根据部门deptId查询学生列表/ T- M" ~! d! y1 A* R6 v+ @
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());% L& k$ ^) w/ R% d6 C. B
List<User> users = userMapper.selectList(wrapper); T, Z, Q! N6 R/ N! I
deptVo.setUsers(users);
0 B9 f6 x d8 Z" h! t}
2 l7 c( C2 y! b: D( s% ?, y( o</code></pre>
( E/ C4 h% C6 C2 N5 |8 O1 s9 R<h5 id="2理论分析-3">2、理论分析</h5>
/ T. g+ C3 I, ~! l# w/ ?+ s<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
# d7 p3 |0 Y' l<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>; r1 @, t4 n- O3 K) b% {8 B( y
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
' _5 p: \- x9 @<h5 id="1示例代码-4">1、示例代码</h5>
% q9 J9 O- h$ k1 k! T( ?<pre><code class="language-java">/**
$ H4 ^! A6 [) b# }+ p * 查询多个部门(其中一个部门有多个用户)) U9 t6 i$ U9 e5 t
*/4 r. K; V, m& ~2 p7 ] `
public List<DeptVo> getDeptByList() {& J4 N- r' ?1 `; b) U
// 按条件查询部门信息
+ g+ _$ s% D. i0 t1 t: |8 p, Y3 | List<Dept> deptList = deptMapper.selectList(Wrappers.emptyWrapper());
) L3 O" i0 Y+ E6 O2 Q( V, ^0 u& K List<DeptVo> deptVos = deptList.stream().map(DeptVo::new).collect(toList());
, h: W% J: r6 F if (deptVos.size() > 0) {. y* p. X" b d& [# P$ v: f
addUserInfo(deptVos);
v; y/ `: q6 H% n5 K0 @ }0 y/ V1 ~' b' y0 w* d0 r( Z
return deptVos;: _8 j0 ^- d( ]" u
}2 e( A5 N f% }- F- _2 g
</code></pre>
5 Y9 v5 P* P( B, G M7 j* j<p>补充附加信息</p>" Q# h, k8 ?5 H: k( E& I
<pre><code class="language-java">private void addUserInfo(List<DeptVo> deptVos) {
; l# p+ u) A6 g$ y+ \$ z' a' b, j# A; [ // 准备deptId方便批量查询用户信息) X2 q6 M1 T* U0 h- U
Set<Integer> deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());8 O/ g. W/ ]% I, l1 r
// 用批量deptId查询用户信息
/ V( v$ s# m" [3 @: U List<User> users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
' v! n) b# X& H7 @" G' X // 重点:将用户按照deptId分组0 t+ b v8 j: V" v) x" P
Map<Integer, List<User>> hashMap = users.stream().collect(groupingBy(User::getDeptId));
4 p! G0 T; O/ h- l2 ?; m5 I // 合并结果,构造Vo,添加集合列表' }: Q4 q; L3 Q5 j9 v5 ?
deptVos.forEach(e -> e.setUsers(hashMap.get(e.getDeptId())));# f1 |8 t9 n0 o3 g1 r
}2 Q9 s$ k% b& z# u+ t3 y& s9 H+ A% x: d
</code></pre>
4 C/ u0 E% F; C5 d/ a5 ~<h5 id="2理论分析-4">2、理论分析</h5>
/ w6 @( V0 z! o<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>3 ]- A' V0 p8 b& W: _
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
4 L e+ K/ V0 y7 o, i& A& O9 E<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>3 _( K6 F6 K1 ]7 Y
<h5 id="1示例代码-5">1、示例代码</h5>' r& w3 R4 ~( j& y
<pre><code class="language-java">/**; Q! c( m# j$ Y
* 分页查询部门信息(其中一个部门有多个用户)! V4 a1 W9 y/ G; D4 ?0 v
*/
/ e* P# j$ F5 k8 A$ ~3 U4 Qpublic IPage<DeptVo> getDeptByPage(Page<Dept> page) {) z3 c' \5 O3 G+ D- J
// 按条件查询部门信息
% |( H: g6 m1 V, M% l& _ IPage<Dept> xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());& u* m5 Z1 z) ^4 f5 L; ]
IPage<DeptVo> deptVoPage = xDeptPage.convert(DeptVo::new);1 Y* \# F' J0 t/ S! E& ?$ ~5 ~
if (deptVoPage.getRecords().size() > 0) {
4 G! N i4 D) D {& K addUserInfo(deptVoPage);$ `8 d t9 H6 D1 A: l5 ]
}3 B, d) g: w3 J1 A" \
return deptVoPage;
8 e; V5 Z9 `8 a0 g8 ?6 n}
+ p- H8 D1 p7 q' l! _, O6 |</code></pre>
# F/ r( d L. O8 X. D& ~7 M# c, d<p>查询补充信息</p>6 l! c4 S g* a! z" ~7 Z
<pre><code class="language-java">private void addUserInfo(IPage<DeptVo> deptVoPage) {8 d! y% D, x; e' Z
// 准备deptId方便批量查询用户信息0 K' [) E- L( m8 p
Set<Integer> deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());- ~& d' ?# d# `9 y% Z
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds); O3 ]8 a4 l* t- M3 A- V X5 c$ Q
// 用批量deptId查询用户信息$ d9 V# a; s2 I; U( c3 s1 O# Q
List<User> users = userMapper.selectList(wrapper);
: Y" [3 z7 I$ r8 A9 H0 F // 重点:将用户按照deptId分组
* H- n7 u' g1 s2 e, i5 ?, w Map<Integer, List<User>> hashMap = users.stream().collect(groupingBy(User::getDeptId));" Z0 s' u4 e1 S$ ?, [+ m5 d; \( F/ H
// 合并结果,构造Vo,添加集合列表
7 k" S2 U! l& }) ]5 n8 M2 l( ] deptVoPage.convert(e -> e.setUsers(hashMap.get(e.getDeptId())));
( M* |5 P5 Q) d: l) ]}
~7 `. b) f1 k; i</code></pre>
# Z! L8 m8 ] V# l<h5 id="2理论分析-5">2、理论分析</h5>1 W; @; f1 ]9 x9 g3 c! E
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
2 t+ K4 ~% o0 c* J, U n<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
& w+ \: ]' s5 _1 W0 a<h3 id="四多对多查询">四、多对多查询</h3>+ H, E8 k- P; |
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
8 z% q$ B+ S" @$ c# `<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
. u7 {# d( S5 f<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>% ]2 H3 ~/ {" W6 w4 a! H) o
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >6 v8 p% n; k6 h) p5 T3 X
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
7 S1 M5 V- U( z/ Z5 K N! H' R( o% `<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
3 q! i9 Z$ d) \* h+ I! |<h5 id="1示例代码-6">1、示例代码</h5>, C4 C8 e2 M& x3 s( H& K* T% C
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {, R, k* }4 |9 J0 g. m8 P
// 通过主键查询学生信息
* A0 k5 q7 j9 g1 O( B, B6 p StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);# x) S& d1 g" F! z4 P
LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);; O N) Q% D7 \8 y r6 N
// 查询匹配关系# V( K- \% j7 A( R& X
List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);+ D, A; C1 y$ ~3 {! s ]0 n' g2 T2 Q. ?
Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
" i7 ~$ z* Y9 [ ~ if (studentVo != null && subIds.size() > 0) {
3 b, V" y; n8 s List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));& p2 o0 Q5 i% @ x
List<SubjectBo> subBoList = ConvertUtils.convertList(subList, SubjectBo::new);, R- V$ L* d Q+ q2 S
HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);
- T3 Y6 ^, L4 ]0 ~ subBoList.forEach(e -> e.setScore(table.get(stuId, e.getId())));6 u5 d' I6 l( t
studentVo.setSubList(subBoList);* z5 l- B/ a4 k2 F8 L8 S
}1 s; a2 v3 X! e/ W, W
return studentVo;( Q6 S; Q, ~0 k, }! l' ]/ k# Q
}$ u2 |) l& g$ p, f# H
</code></pre>$ T! v! {9 N- R3 n' C
<h5 id="2理论分析-6">2、理论分析</h5>
# N. p/ S7 F2 N# w/ J' g! Q<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>( {/ C3 i$ }9 c3 z& c O
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>! n* @2 v1 h z! g( n5 V
<h5 id="1示例代码-7">1、示例代码</h5>
5 M3 A2 n, S( [<pre><code class="language-java">public List<StudentVo> getStudentList() {
% D' q: ^( i" _, p# w6 n // 通过主键查询学生信息
! G7 v$ J: g' `2 K; P" k List<StudentVo> studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
6 i" w) N+ v' m3 o: t. a# Y' w // 批量查询学生ID* \) w( G% o; I" g7 _# D7 j% j. J
Set<Integer> stuIds = studentVoList.stream().map(Student::getId).collect(toSet());. S9 a! e& [5 W0 G
LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
2 F% ^1 G( O' t7 r. { List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);$ Y) T) F6 s2 {0 B
// 批量查询课程ID. n8 t4 I3 N( y6 t6 u% y, q8 f
Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
/ V4 B' _( w4 r5 d if (stuIds.size() > 0 && subIds.size() > 0) {
& x9 _ p; v% ]" m HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);! h! g9 h3 ~4 W! {& J0 |- S; y
List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));; l0 t% k5 `3 v0 B5 o' d
List<SubjectBo> subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
7 B% n' z( i2 D+ j; c* k$ @ Map<Integer, List<Integer>> map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
: M' e, D. s8 R1 _2 P# G- X9 \0 Q for (StudentVo studentVo : studentVoList) {
# V9 P- w* s- m // 获取课程列表
( s' }* I; T# w( s8 n) t List<SubjectBo> list = ListUtils.select(subjectBoList, e -> emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
7 F d' B7 Z. B: |+ ~( ^% v: b // 填充分数
; H: s" N: T. S {" c2 {) ^ list.forEach(e -> e.setScore(table.get(studentVo.getId(), e.getId())));
" R. m4 ~! m0 g# z9 d1 K( U: w studentVo.setSubList(list);, w& o8 g; k2 \( D3 S0 ]! Q
}3 H4 _9 C/ Q) l' r# s8 _. q
}
/ m+ _7 O/ s, L& S* a6 } return studentVoList;
+ V7 ?( u8 L* z1 R}
: ^! {, ^& l4 C1 n- |0 p* ^# V</code></pre>5 h, S8 Y) S( l
<h5 id="2理论分析-7">2、理论分析</h5># \% C E5 i. L; u
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>8 M6 Y% j8 O5 M) g! o! X" [# o$ S
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>' a/ Q, h2 q' Y5 ? A
<h5 id="1示例代码-8">1、示例代码</h5>' l" j1 C: A7 K* T+ }
<pre><code class="language-java">public IPage<StudentVo> getStudentPage(IPage<Student> page) {( i) L' H' i, g; W G5 v
// 通过主键查询学生信息
' k( d, \2 l+ ]! N/ ?& [" ?6 d& S IPage<StudentVo> studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);/ a' }& L% N4 n
// 批量查询学生ID
( O% `9 w- T1 u+ H Set<Integer> stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());' k9 o( I" { z0 R ]. c
LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);' p! d* T; P6 y* j1 ?; n
// 通过学生ID查询课程分数
. J, H9 c3 Q/ ^* ~% e+ Z List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);; e- r' _" w, g& J
// 批量查询课程ID* [- v% }/ R& I- J% o t
Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
7 V* d1 b/ | o if (stuIds.size() > 0 && subIds.size() > 0) {
% V6 [, N: `2 h, z5 ? HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);/ K- y0 y8 g- e% Y$ X
// 学生ID查询课程ID组
. ^9 L. k/ P3 K2 H% a Map<Integer, List<Integer>> map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));) { A" Y" c/ u$ s5 R! m8 I$ ?
, |5 x& Z9 i0 i+ e4 } List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
+ V% n, w/ b& [ List<SubjectBo> subBoList = ConvertUtils.convertList(subList, SubjectBo::new);8 Z1 ~+ A' S* ?+ }9 @; j6 r
for (StudentVo studentVo : studentVoPage.getRecords()) {6 m; y5 l, u% i! d2 A- \; e
List<SubjectBo> list = ListUtils.select(subBoList, e -> emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
( n* B3 V Y3 E _6 D$ d list.forEach(e -> e.setScore(table.get(studentVo.getId(), e.getId())));
( E8 w5 G# N C; L studentVo.setSubList(list);
6 V$ [9 Y7 M+ f+ }: C. [- O* m }
+ U* I' \" u( F# O. ^' w5 G m }
! T1 t4 @+ H7 a return studentVoPage;
3 Z/ a( c W a! ^4 ~. u- h: o8 x8 K}0 K. z9 I/ z4 ]' j/ ]' |% R/ q- p
</code></pre>
2 b# x j* v0 T* f; V8 C<h5 id="2理论分析-8">2、理论分析</h5>
( a( `1 T# n* C<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
# ]0 a0 G# @$ @" P<h3 id="五总结与拓展">五、总结与拓展</h3>( q# E* y+ M1 }: W" k% }
<h4 id="一总结">(一)总结</h4>4 o. {+ K7 `) K6 F
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>+ s3 e( } i6 M2 o5 J
<ul>7 X7 f, t- z C
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>6 ~+ i7 o+ I4 Y8 P9 I
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>& F/ G" Z, c b% D. V+ V. x
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>+ C& a0 T9 Q+ L7 d. l
</ul>1 `8 S7 s1 t6 r
<h4 id="二拓展">(二)拓展</h4>
2 O0 Z: j5 W. K$ Y8 g; d<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>- s6 G4 ?; Q( p- L: D
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>7 g+ e' B- [4 p: T7 T
<ul>
/ ]+ s( F+ j2 C6 w& z<li>当数据量较大时,仍然具有稳定的查询效率</li>
$ l9 {$ e# Q! K! g3 n</ul>
0 ^7 k" m, ]8 C+ r7 y( q% w* B# R<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
6 Y; [- R" K+ A; H2 ?<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
' z# y' q/ P0 @8 l$ D( }( K8 ~. h: ~<ul>
6 a- O. u7 e; A! G% j' ~' q G<li>与二级缓存配合使用进一步提高查询效率</li>
( u, h$ _2 R0 b+ f& i8 G6 Y& R</ul># f1 u, c; Q+ K. D
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>: G+ t" G, v% G$ v
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p> R7 H! E) e8 H+ l! y' b
3 |/ c$ L7 u# d |
|