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