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