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