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