|
|
: h4 _& W& d/ I+ Q- X<h3 id="一序言">一、序言</h3> {0 X7 p. i" _1 i7 p
<h4 id="一背景内容">(一)背景内容</h4>
& l; Z/ E, t8 Z, m<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
) M5 `4 z8 P/ K/ [) x<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
1 F- |9 ]2 t! \( t5 X0 S$ V& h5 ^<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
5 l$ R3 {3 U" T- Z" z' G+ H<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
6 A+ Y* `# s- o<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
+ d7 b: z4 A8 c<h4 id="二场景说明">(二)场景说明</h4>% }8 Y/ w3 s( G8 u3 d
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
# q6 Y: T6 ~% W% R$ {- l<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >" ~1 [$ Y& I) n# f; l
<h4 id="三前期准备">(三)前期准备</h4>
- E0 b# o9 Q/ Q! {1 w9 Q: A7 X<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
1 f# l3 t: n9 R2 ^<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >' q d6 } h: Y" z2 t
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>4 ~# z0 Y; F; }6 U
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>, v9 ?! w9 G4 x
<h3 id="二一对一查询">二、一对一查询</h3>( Z$ Z+ _* S8 m- E `" U
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>: m8 h( A, `1 ]
<h4 id="一查询单条记录">(一)查询单条记录</h4>1 T" |- ~" j2 p+ {! @/ W6 e
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>. g- C1 c7 O8 ^4 z$ j" X
<h5 id="1示例代码">1、示例代码</h5> Z6 N. \( @& @, ^- D0 ^8 C" Z7 q
<pre><code class="language-java">/**
1 n( g: W, m- W4 e& n( C2 u * 查询单个学生信息(一个学生对应一个部门)
" |6 d+ j5 q" [6 l( `! @' a */
# z9 r0 Y0 ^$ N" O5 jpublic UserVo getOneUser(Integer userId) {7 n6 U6 v6 T" Z/ J5 T
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class)/ ]% w( z& G8 B- z7 [ r X8 f
.eq(User::getUserId, userId);
- m. I! i3 B% M% x // 先查询用户信息
+ h5 f4 j0 a% b1 H8 j, ? User user = userMapper.selectOne(wrapper);- ]4 i2 V# x9 p! E; Z+ }
// 转化为Vo
# U0 P" k# k& ?; c7 e0 y UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);+ G( g& D" r/ G
// 从其它表查询信息再封装到Vo
5 l6 r2 L6 v6 ]- |/ F1 a/ r Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
6 ]5 {( j$ y. W: q( A. J return userVo;" ^8 u3 M: _0 L6 }1 _% A. D* x
}$ n/ A: N( r/ a" M9 r
</code></pre>
3 [; N* O1 O: M7 E% K! k# J<p>附属表信息补充</p>
, |# }! W/ J0 `' s1 N<pre><code class="language-java">/**9 e5 K' n# |, x
* 补充部门名称信息4 a$ E7 C7 ?! s! L7 B8 @. e
*/
* ]6 o9 e5 k( U% _4 bprivate void addDetpNameInfo(UserVo userVo) {7 l0 n& F% i3 V {/ t9 I+ O6 W; L7 U
LambdaQueryWrapper<Dept> wrapper = Wrappers.lambdaQuery(Dept.class)
5 P$ O- j' j3 K% W2 M: b* O8 b2 N$ l .eq(Dept::getDeptId, userVo.getDeptId());# L% W2 I2 n, T/ R
Dept dept = deptMapper.selectOne(wrapper);$ c$ k' y$ P8 L( U l( N* Z
Optional.ofNullable(dept).ifPresent(e -> userVo.setDeptName(e.getDeptName()));
/ O' e" ?/ _5 y! g" C9 I/ Z4 U}/ N! f2 r# B) x8 P! C" {( Y: h0 q
</code></pre>
& \) S& y) x, g2 E! H7 u; d<h5 id="2理论分析">2、理论分析</h5>
0 ~8 O9 w W4 `3 ~( o- }<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>" C/ g# Q b- d' G5 ^
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>! W6 a3 |( p& @) ^; z
<h4 id="二查询多条记录">(二)查询多条记录</h4>
& H# z8 h* {7 a$ n4 M6 V* I5 k. j# [<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
8 K4 ]- |4 }( c) r<h5 id="1示例代码-1">1、示例代码</h5>
5 s. j: M: r- F& N; p' w: Z<pre><code class="language-java">/** e1 O& A2 @) r0 ]& H+ k4 F' g$ J
* 批量查询学生信息(一个学生对应一个部门)
8 o1 G5 S' t: d7 l& B8 U$ Z1 k, u */" t( L, ~3 M. ^$ b. a
public List<UserVo> getUserByList() {2 i6 r. S5 f% }0 |# J0 M5 g
// 先查询用户信息(表现形式为列表)( ~1 g& T, W0 V6 ]& w4 _3 @9 Q# e
List<User> user = userMapper.selectList(Wrappers.emptyWrapper());0 h+ S0 t" ]9 K. k
List<UserVo> userVos = user.stream().map(UserVo::new).collect(toList());8 N% D, \ f. }' P* [+ W0 w
// 此步骤可以有多个" z0 {: B. h' u& F
addDeptNameInfo(userVos); ]% [" _# ?- e" H" M
return userVos;# k2 g) }( \! G4 m
}, T n) A1 Y" M; ^) U
</code></pre>
8 {* d# o+ V) }; W9 q% E<p>附属信息补充</p>- K: ?* k: V: S5 p; u) \2 f; R
<pre><code class="language-java">private void addDeptNameInfo(List<UserVo> userVos) {; p G' N- ^; W' U. A, a _4 t, l2 x% m
// 提取用户userId,方便批量查询
& _/ }& D) _5 ~ Set<Integer> deptIds = userVos.stream().map(User::getDeptId).collect(toSet());% B0 B$ |) H; K6 g0 D
// 根据deptId查询deptName(查询前,先做非空判断)% m: h3 d5 P( b, b* Q! D1 b, Q S
List<Dept> dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));3 ]0 n" M& y" I4 V+ `7 r- n
// 构造映射关系,方便匹配deptId与deptName
, i, G' P9 j4 \* j8 c Map<Integer, String> hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));: v5 T& L; l' S
// 封装Vo,并添加到集合中(关键内容)$ m$ L+ o/ i4 j/ X0 h! f
userVos.forEach(e -> e.setDeptName(hashMap.get(e.getDeptId())));' F) g5 N" T- w3 f7 V5 C
}
/ [5 `6 ?3 @) ~' C</code></pre>
4 r/ b. [* H8 b9 R' R/ m<h5 id="2理论分析-1">2、理论分析</h5>8 _. D0 B+ V, `. `# J6 v
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>" E1 R( {2 s% X; s2 O
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
$ q- g, D% O" E% C9 ~<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>8 ?8 I: R9 K; f- w6 ]6 N
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
% n! m W3 i+ T& B, J+ t<h5 id="1示例代码-2">1、示例代码</h5>5 d9 T4 ?- s5 u6 H
<pre><code class="language-java">/**
7 ^6 q: k+ F: R * 分页查询学生信息(一个学生对应一个部门). f( Y( X8 M% {/ c' Z( D
*/; o) }8 C, n, H
public IPage<UserVo> getUserByPage(Page<User> page) {
: D/ @! V& v9 j& g9 q$ {$ F // 先查询用户信息
) o! n6 X5 p- E7 f. V8 s; F! ? IPage<User> xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
; j. J" B; d: T/ s( Z3 ~ // 初始化Vo
' g! ^3 n, H' w+ b! A IPage<UserVo> userVoPage = xUserPage.convert(UserVo::new);4 O. w/ W4 h, l) L- r/ ?/ `
if (userVoPage.getRecords().size() > 0) {- u7 c" S6 B* V+ o- _
addDeptNameInfo(userVoPage);7 A& l& K4 O4 l9 J% Y2 T+ A
}
) q6 g, P+ G% c" C |* t; _ return userVoPage;
C6 g- F" i( R5 Z- O}
- r$ t3 T+ ?( s, [: q6 k</code></pre>$ P% u& |+ h9 r, [+ Z! A
<p>查询补充信息</p>6 \+ c" L& N7 k4 j# Y
<pre><code class="language-java">private void addDeptNameInfo(IPage<UserVo> userVoPage) {1 o% v( y" I) ^, ?8 y
// 提取用户userId,方便批量查询+ q2 d! K* X. o( e5 M9 L
Set<Integer> deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
. ^! \' M: j- P3 q1 h // 根据deptId查询deptName- Y& Q8 h2 S- M: m
List<Dept> dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
9 @& G- L% _ N9 e% r' g // 构造映射关系,方便匹配deptId与deptName; U0 t/ n* D. f
Map<Integer, String> hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));$ j) M. `/ _8 _6 B4 g
// 将查询补充的信息添加到Vo中
8 W2 f. x. \1 Y) E/ c userVoPage.convert(e -> e.setDeptName(hashMap.get(e.getDeptId())));) q1 ]/ u5 V, O; o- y0 H
}
/ `, p9 i0 w3 W/ z9 h8 ]</code></pre>1 ]' Y' X9 h4 s& n( W& |0 T
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>2 C! T7 w+ q X
<h5 id="2理论分析-2">2、理论分析</h5>
r7 P3 [. F1 a) F& [7 P2 d7 Z<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
1 }8 k$ N0 \; s& Y<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>" Z* a+ z9 T% S4 g' G- g, m& L
<h3 id="三一对多查询">三、一对多查询</h3>1 M4 `2 G' c0 M' V
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>2 n9 C, e; b$ {+ J$ R4 S
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
; b: F5 g8 }4 J<h5 id="1示例代码-3">1、示例代码</h5>, H5 l4 u" k7 U3 z6 \
<pre><code class="language-java">/**
@- e2 e5 B2 J8 v& @% m9 J0 K * 查询单个部门(其中一个部门有多个用户)
6 c( }# F, P% I R) Q& \7 u# {; Z */# @$ S0 o; c( H2 \! r' ^5 W
public DeptVo getOneDept(Integer deptId) {
4 L& `. _! Y" z2 _/ s- A S // 查询部门基础信息5 u/ y6 D" T0 p5 `7 R9 e6 S
LambdaQueryWrapper<Dept> wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);+ L$ I9 p" a) \) n5 u
DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
8 Z5 S& }0 N' K" Y$ a Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);- d, l9 c' \: F9 S, Y- p
return deptVo;: K* R0 Z/ b2 C2 K
}, _- Z* X3 g# D
</code></pre>
6 i- _6 p0 c5 Q" F: K% J<p>补充附加信息</p>
! S* I- A6 U% V/ `! E<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
" k' _5 F0 i+ z" s+ h C // 根据部门deptId查询学生列表5 Z( L _% q ?0 b2 x& R+ L- x5 V
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
6 K, ~0 p" Y' i& K" F7 k- Y List<User> users = userMapper.selectList(wrapper);" G; I$ O6 r8 q9 d
deptVo.setUsers(users);, I) a# u% I( \
}
' c$ [: ^; g$ h* _$ @. e</code></pre>
5 T: c) n3 v w) ?3 y* ?, n0 Y<h5 id="2理论分析-3">2、理论分析</h5>* s7 c6 Z8 \/ P) h( S, \4 b$ r
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>2 m H& u6 M: a( } x4 k( A
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>5 O2 k. i: ~( A% l c1 {
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
3 v: C4 e. R0 s1 ~; Y3 T<h5 id="1示例代码-4">1、示例代码</h5>
7 U0 J( F. O% E+ p& x& {8 n4 ~<pre><code class="language-java">/**
* ~& @3 [, E* j$ y! i9 o: ? * 查询多个部门(其中一个部门有多个用户)
, i+ W: W4 `. @" Q( f v% y( J */
* r3 U* _) e. `4 c" x7 Hpublic List<DeptVo> getDeptByList() { Z/ Y0 F$ V& t0 C1 y3 K
// 按条件查询部门信息: X& f* h, m# B# N$ a! W! Q
List<Dept> deptList = deptMapper.selectList(Wrappers.emptyWrapper());- z+ \, d9 a: K0 a# |
List<DeptVo> deptVos = deptList.stream().map(DeptVo::new).collect(toList());
$ T3 I+ w" N) O/ E% p if (deptVos.size() > 0) {% e! {) o6 w: ~+ c& N
addUserInfo(deptVos);' `' H# x1 V8 s; E; `" j
}$ t9 c$ j- |( I, Q: r# j" f
return deptVos;
, B4 r( B% _% P+ C( I}+ S& @6 s* _! D; C3 e
</code></pre>
+ t" |. v5 _% T" c f; B<p>补充附加信息</p>
C& t( O6 c Q3 |3 d* {' d<pre><code class="language-java">private void addUserInfo(List<DeptVo> deptVos) {
$ F; f" ]+ Y2 F3 Q4 B4 K& g // 准备deptId方便批量查询用户信息1 s4 q! ^6 R0 |
Set<Integer> deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());3 A6 e0 W1 }, k* O
// 用批量deptId查询用户信息
. u" k/ S/ T' F" M, j List<User> users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));) k! \7 V4 c; a9 q
// 重点:将用户按照deptId分组. Z% D: y( J& \4 @7 Z5 o
Map<Integer, List<User>> hashMap = users.stream().collect(groupingBy(User::getDeptId));
9 v( G6 J$ [8 \ // 合并结果,构造Vo,添加集合列表
2 M7 i/ ^2 e' T* d) w7 B deptVos.forEach(e -> e.setUsers(hashMap.get(e.getDeptId())));1 F6 _- f# l$ s) ]
}
* _( j6 b; r$ L% |- W/ @2 I: A</code></pre>. W/ g6 L: `' D
<h5 id="2理论分析-4">2、理论分析</h5>! b8 k& C' K e0 g: M, Q
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>3 G( x5 ^9 v! P" d5 P7 i! \% O4 s
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>5 w# ~: ~) p; [
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
! k) s" E! g+ l2 n<h5 id="1示例代码-5">1、示例代码</h5>
' z7 V6 l$ N( ^# `6 o5 G% U- M<pre><code class="language-java">/**
; u' u4 T/ v3 j7 _4 @ * 分页查询部门信息(其中一个部门有多个用户)' \: _0 j5 k8 J N4 U. e' w* C1 `
*/% s9 S6 G5 A$ e, J
public IPage<DeptVo> getDeptByPage(Page<Dept> page) {% I! n5 c7 T6 M7 F) r& }$ e
// 按条件查询部门信息! V# k% T7 @0 ?, E
IPage<Dept> xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());# Y3 S6 f0 s1 N6 |9 J- i* M2 r
IPage<DeptVo> deptVoPage = xDeptPage.convert(DeptVo::new);
9 ~! i3 G+ l! V9 q, y2 z9 ? if (deptVoPage.getRecords().size() > 0) {0 ]. r: C# l+ I4 u$ e! v. Z
addUserInfo(deptVoPage);5 [+ v" J( {! \9 o1 N8 e
}
5 k' X4 S% f8 Y% V3 i& A5 a return deptVoPage;
' O# x) F, D8 g2 e}9 H5 T; }+ p; D
</code></pre>/ B1 W+ P# e! ~
<p>查询补充信息</p>
: o+ p0 E! b0 J6 |- h+ _<pre><code class="language-java">private void addUserInfo(IPage<DeptVo> deptVoPage) {2 V- a- \# n3 X; O4 f/ J" N
// 准备deptId方便批量查询用户信息) }5 s. g3 B! X; |& [% m/ q
Set<Integer> deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
' p& I. K9 ]/ L7 F, ?& I( i ]1 b LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
" \ B8 r$ T# Y# H // 用批量deptId查询用户信息3 |6 C, P' t2 G$ n8 o. s! d! V
List<User> users = userMapper.selectList(wrapper);
; U; V- A2 Z# [7 G/ g // 重点:将用户按照deptId分组
' j) P7 ]. C a2 V9 j$ m5 z( x- D Map<Integer, List<User>> hashMap = users.stream().collect(groupingBy(User::getDeptId));
. f- M+ Z3 b# X3 s1 q/ M/ r) z+ L // 合并结果,构造Vo,添加集合列表. M2 U$ A+ I! W7 z4 c# n
deptVoPage.convert(e -> e.setUsers(hashMap.get(e.getDeptId())));$ c; _" ~7 j U; ]% r6 q9 ]
}5 T1 L$ O& k8 g5 S* d
</code></pre>$ D1 O: R2 K5 ` L: i
<h5 id="2理论分析-5">2、理论分析</h5>
- A$ O' m; @. X, X% Y- i, Y$ C% P<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>, Q- k8 ]# B: W0 A7 X
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
" E9 z- M- A, Q x8 D0 N<h3 id="四多对多查询">四、多对多查询</h3>1 |9 p7 N/ W. d6 b U* \& j
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
+ A/ V# K4 r. S* A! @<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
0 w2 m6 `' ^7 A# ^% }<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>' ?) @ z! {7 F5 C: d+ s; R7 x
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >" ~% h7 B/ s5 o, s5 a' \
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>3 l% R+ T5 ?- { m1 X. q; P0 N
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
) M; V1 l2 P4 \- d9 [<h5 id="1示例代码-6">1、示例代码</h5>* L5 |) `" I5 E% X Z, C
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
9 W9 I$ O2 ]7 k6 a$ m/ d // 通过主键查询学生信息' @6 E2 A) L3 Q- X- j
StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
; K& L1 S( c& t1 |0 x3 N$ D6 | LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);3 ~1 s b1 `. L& r0 A* R9 H- ]( V
// 查询匹配关系/ E0 N d9 Y) ?$ ]
List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);: ^' f% ^3 x& ]9 P9 I4 r
Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
2 c4 c0 r1 c$ x if (studentVo != null && subIds.size() > 0) {6 [% o* B5 i+ N: D8 Z- t
List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
( T6 W( {6 e3 w5 T# h List<SubjectBo> subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
4 z+ E3 r$ K! q3 u, N! @ HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);5 o. H& [. J+ Q0 M0 |
subBoList.forEach(e -> e.setScore(table.get(stuId, e.getId())));
3 ? H2 ?5 L5 C. Z% @ studentVo.setSubList(subBoList);
5 l% k2 O' X% T2 j }
* ]/ o- L/ K ~0 {1 R7 z return studentVo;
. h; H( }6 }, {9 \# y$ ^}
8 d2 e" e; h' O6 V5 I( o2 d</code></pre>: b1 }% C& L, U; u1 n$ ]
<h5 id="2理论分析-6">2、理论分析</h5>0 n; Y, z! Z( }( |* b
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
. r& H& r8 v& n) Z<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
) G& C# C* r& K0 h7 w$ P7 H1 Q<h5 id="1示例代码-7">1、示例代码</h5>
$ P# O' u' O3 J<pre><code class="language-java">public List<StudentVo> getStudentList() {
. f6 M1 [3 R0 b* j // 通过主键查询学生信息6 z5 i( v* i' j( y. P( c- E) z
List<StudentVo> studentVoList = ConvertUtils.convertList(list(), StudentVo::new);6 P7 r$ l* h0 ~* [* V
// 批量查询学生ID, p. @9 @. `! j8 T9 n
Set<Integer> stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
7 _/ R2 b8 R L LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
5 ~# y5 E( a* ? ^5 X! u- `, U List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);
; G6 \5 [. Y4 ~9 L7 l // 批量查询课程ID
, t( ^- d6 v) ?$ n0 \: I Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
0 V% F( x6 F* p, X+ ^ if (stuIds.size() > 0 && subIds.size() > 0) {* {3 d" E' y3 z6 ?+ Q
HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);# ~: C* g- \/ E
List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));! J: N) i* f9 h; ~
List<SubjectBo> subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
( D$ @& N: }/ T, |" s9 ]2 E1 u Map<Integer, List<Integer>> map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
: V' o# O4 D+ f/ L# U. U for (StudentVo studentVo : studentVoList) {+ ]. \+ d' D) c& b
// 获取课程列表/ `3 `" W6 i2 @8 k. m4 H
List<SubjectBo> list = ListUtils.select(subjectBoList, e -> emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));2 [. h' ?' }2 \4 I
// 填充分数
8 x$ p4 f9 k) c1 X list.forEach(e -> e.setScore(table.get(studentVo.getId(), e.getId())));- }2 A/ V5 ]& r8 H
studentVo.setSubList(list);, b" ^+ P; I# H/ V l" e# c
}
$ R1 @ Y8 b7 o }
4 \7 u1 z6 D7 Q# A* z return studentVoList;+ Z# ]1 t: [! r0 p
}
0 }; `/ E2 P ~) N: G</code></pre>5 H) |) n1 i q
<h5 id="2理论分析-7">2、理论分析</h5>
. _/ W, e6 o( d5 v<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
# I- o0 d7 N) x* O! p0 ~3 o ?<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>0 N+ H, p1 M1 B' j: s; a5 }
<h5 id="1示例代码-8">1、示例代码</h5>* G- W1 J0 f: A% n% j* V
<pre><code class="language-java">public IPage<StudentVo> getStudentPage(IPage<Student> page) {
5 X& |7 Y0 h% H; c' C // 通过主键查询学生信息' x) \( k+ T6 g! G
IPage<StudentVo> studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);; K% {- }* Q9 j" H$ V2 y R
// 批量查询学生ID& ~9 h$ ^% N- P4 s. v5 {- l* A
Set<Integer> stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
9 k5 h" |" B: \* T LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
6 k! I8 ~$ i, z. r) r // 通过学生ID查询课程分数
, @& @; s6 z$ G* R/ k2 Y6 K9 l List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);6 L4 d* s6 Q( t6 L- o" x! h
// 批量查询课程ID, _4 m' t( ^2 c% o& A* h% `) ~% h
Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
v( o8 q, R# Y+ v$ S if (stuIds.size() > 0 && subIds.size() > 0) {8 ~# f0 I. ~% J% D
HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);
0 O Q# p' l* S- R% U // 学生ID查询课程ID组
; N5 @4 Z8 f4 t# P f Map<Integer, List<Integer>> map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
# @6 N- U5 m) |2 W3 L* J4 l' u1 Q# h0 N9 e4 {8 p
List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));1 V6 V6 M8 w; D9 L" Y
List<SubjectBo> subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
* ~3 H( r2 O; B2 B9 k for (StudentVo studentVo : studentVoPage.getRecords()) {: s2 o2 X2 D" _) ^- d9 U# g
List<SubjectBo> list = ListUtils.select(subBoList, e -> emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
5 N) M# _- I4 w! N% m list.forEach(e -> e.setScore(table.get(studentVo.getId(), e.getId())));2 U; h% G: M' B' G
studentVo.setSubList(list);" f; x8 |8 q3 t2 M. C
}
! ]( { \1 s) p/ z* j9 a }
8 I, z U( S0 [( l$ ^ return studentVoPage;
( G" h; T6 j& g: w# W}2 \& `3 T5 q8 J8 H& X6 s- G
</code></pre>
5 o1 E+ j# R3 o<h5 id="2理论分析-8">2、理论分析</h5>
9 R/ h* ~4 N: @$ r. ^0 } D<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>+ Z) |; B* ~' z- A% V
<h3 id="五总结与拓展">五、总结与拓展</h3>+ ]4 j. C+ |3 W
<h4 id="一总结">(一)总结</h4>
# ~" S" U" ` m0 Z2 z<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
7 q' N3 V+ X0 V! c# K- y5 Y& ]<ul>
5 Z r* l# }9 q2 u1 Z/ T: N<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
8 E8 ?, c) d/ j- U$ f) n<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
+ p. e5 ~ K7 j% G' u; R7 W5 _<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
4 ^9 D2 v7 b V- B8 l% U</ul>$ T( T' E) U2 _
<h4 id="二拓展">(二)拓展</h4>
$ M" H* ]0 j e8 ?8 A<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>2 l5 p) x5 \2 | g. T: x% ^5 C# [
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>* C/ A# r8 H3 }8 M0 H& _/ I4 S
<ul>. ~ E: f' I9 e$ m b0 A; a0 L
<li>当数据量较大时,仍然具有稳定的查询效率</li>* p! B) X9 E; s' [6 x1 c2 ?0 B
</ul>+ B" [. t1 i# K8 e! t2 [8 t) _
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
2 w/ Y1 i k# ^* M. D<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
/ G9 h) m" a1 K4 R: ^0 w7 {9 P<ul>
5 L3 |/ S) H2 E+ Z, C<li>与二级缓存配合使用进一步提高查询效率</li>
. S- F9 E8 M* P- G' R</ul>6 n) ]1 J. i( M9 f6 I- P. p
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
. l7 u: N5 f* E3 ?. C5 r; R- H' R0 W. X<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>; ?: F9 r1 c$ Y* d/ h x! \7 c( S
% c, g- M+ Y. S$ ~$ d+ y' _* R$ j
|
|