|
|
8 z" H/ L$ N- e: w1 y2 K
<h3 id="一序言">一、序言</h3>
9 {- H& ]6 e; j# [<h4 id="一背景内容">(一)背景内容</h4>
2 X: s6 g" _( k8 [* Y<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>& M5 x* P" k2 l$ q
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
6 Z6 \3 X9 T+ I6 m( E<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>$ K* }: J* V" x4 I P: }
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p># F# ~- K% B/ z' i9 D5 l
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
6 H$ ]& X) [2 s2 j& ^1 P% I; U<h4 id="二场景说明">(二)场景说明</h4>
6 o: O) w4 n- n% h q+ _<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>6 W1 ^( V- \( e' }- V, A
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >/ C1 a- } X. }! |' O/ e+ i7 h! k
<h4 id="三前期准备">(三)前期准备</h4>
: P7 b, ^: H; ^- U4 j2 @<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>, \' U* L! Q0 ]9 @$ \
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >8 {( Z4 \# F5 ]) ?
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>5 Q! Y+ i! [$ j( ]/ ^
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
7 Z6 t$ \, K& ?3 {( z<h3 id="二一对一查询">二、一对一查询</h3>
) y$ W3 ~! F) O1 |: x# c<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
0 [/ u0 J& q) V* u, G0 P N, b D<h4 id="一查询单条记录">(一)查询单条记录</h4>
3 \. @# T; ^% G<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>% j6 P$ r; J: I1 d' I) L
<h5 id="1示例代码">1、示例代码</h5>
& o0 Y; d' c$ ]8 p. x<pre><code class="language-java">/**+ W( e1 l' B5 t- I% n
* 查询单个学生信息(一个学生对应一个部门)2 r$ k% ?8 N. r0 r' i
*/
& U* B6 n: N+ m+ gpublic UserVo getOneUser(Integer userId) {$ l( ~9 k- C/ C! q9 h- C' {0 N3 Q
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class)' ?% C7 | f7 k9 n
.eq(User::getUserId, userId);
' w5 K" F1 W* ^! i5 d* \" V% D9 @6 ^ // 先查询用户信息' g/ `( F7 S1 g. z4 h! j
User user = userMapper.selectOne(wrapper);) O3 F7 v/ _; C) N
// 转化为Vo8 _7 R, r$ `5 b2 y1 Y) `: N
UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
; n- b& Q# h. o // 从其它表查询信息再封装到Vo1 _5 `, {& X" c* W
Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);* w) \9 o: C- H( E4 l9 s1 M
return userVo;" ^% E& N6 Y5 O4 ~* E0 S: \1 K
}
. n& f; T' C: Z( `$ S* ~+ N</code></pre>/ \/ ]% @/ B& z3 a/ A5 e4 n$ W
<p>附属表信息补充</p>
; j9 n$ }. N" R; ?8 j<pre><code class="language-java">/**( B+ g4 x2 R1 o, ~% u% _
* 补充部门名称信息9 E7 z+ t2 ?/ e1 Z/ v) n$ d2 C& w
*/
+ H8 s, f' j4 [private void addDetpNameInfo(UserVo userVo) {8 U0 S/ v3 ~ B. [
LambdaQueryWrapper<Dept> wrapper = Wrappers.lambdaQuery(Dept.class)
' `* X; q' {3 h1 X .eq(Dept::getDeptId, userVo.getDeptId());$ Y% ~" Q5 J, G# R- r7 A* P3 Y/ f; Y
Dept dept = deptMapper.selectOne(wrapper);/ @6 d a# J0 ]# O
Optional.ofNullable(dept).ifPresent(e -> userVo.setDeptName(e.getDeptName()));
" R: D' q1 k. @1 ]# K4 U}% M. D- ~ H( }+ x$ t- h
</code></pre>
* Z; l/ |3 P4 t1 ~<h5 id="2理论分析">2、理论分析</h5>
" ]9 \5 x6 G6 a8 U- \! c, f<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
7 \9 i9 U; i5 _4 {; ~* a; A<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>; {( f; {8 U9 Z& w& ~
<h4 id="二查询多条记录">(二)查询多条记录</h4>- F" T4 S$ h* U1 X: W3 K0 j% d. r
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>& x! H% M0 u7 M9 Y* f0 v+ v ^
<h5 id="1示例代码-1">1、示例代码</h5>" a) q9 U* D" k& B
<pre><code class="language-java">/**
$ ] X' U& d9 W9 p u( g* h * 批量查询学生信息(一个学生对应一个部门)
]. {" x4 O* h R" I */5 e" s7 U+ I7 Y6 L& J5 x
public List<UserVo> getUserByList() {0 d2 S/ t I5 Q, O4 p
// 先查询用户信息(表现形式为列表)- M o4 s, l' [5 }# a! c
List<User> user = userMapper.selectList(Wrappers.emptyWrapper());/ ^, k& Q% h/ }3 m# }' \+ w2 R0 b
List<UserVo> userVos = user.stream().map(UserVo::new).collect(toList());% n1 v! M t- s
// 此步骤可以有多个
; {! G4 A8 z8 d5 I addDeptNameInfo(userVos);
9 ?- `: a; P7 z: E! u return userVos;
& c' P4 J! K1 [3 U3 {5 [ z}
) I3 ]8 Z- l8 I</code></pre>
: Y$ j E: |. S1 F4 b<p>附属信息补充</p>
8 p$ d; p- y; x& ]# \9 z8 z<pre><code class="language-java">private void addDeptNameInfo(List<UserVo> userVos) {
3 S6 {# `' p* L# A' z/ Q // 提取用户userId,方便批量查询: d' \9 y* i. L- M( f
Set<Integer> deptIds = userVos.stream().map(User::getDeptId).collect(toSet());" k2 I; M- n# z& i8 j+ @4 z9 F
// 根据deptId查询deptName(查询前,先做非空判断)
" p; t4 R5 h6 U' W) s% y' P List<Dept> dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));9 G5 g; h6 n [/ H! Y
// 构造映射关系,方便匹配deptId与deptName" s9 P. }: d; e- O" t) P5 v
Map<Integer, String> hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
" }7 T- |: K! D W3 g3 i( _1 ~ // 封装Vo,并添加到集合中(关键内容)
5 V! Z3 n D& x userVos.forEach(e -> e.setDeptName(hashMap.get(e.getDeptId())));
' m' E. F4 N; `/ L$ C}
* S4 G R0 Y9 e0 l3 a6 U s</code></pre>8 [1 ?! y2 O$ R0 r1 S; k# i
<h5 id="2理论分析-1">2、理论分析</h5>
) {5 C7 R6 w4 q6 _<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>/ ~. w1 u: p {* n- _7 i" Z. x
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>1 Z1 {* ?5 J" C. O: I
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
* o5 J/ J. V) K: G6 r, \& H. D" E! D a<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>0 k! l' y; f) S/ A: y7 R0 J
<h5 id="1示例代码-2">1、示例代码</h5>: D1 j/ b$ ~6 z, j
<pre><code class="language-java">/**% K1 }- o; X# ~. o
* 分页查询学生信息(一个学生对应一个部门)- ~% D V1 t! x- w8 K
*// w* p. }, }/ {# F! k* D: |, J
public IPage<UserVo> getUserByPage(Page<User> page) {, ], _6 y6 u1 n5 O* O0 t
// 先查询用户信息
7 d: a6 j! A6 \; g5 s/ F, \ IPage<User> xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
2 X3 B" N* L$ f! v6 I+ u // 初始化Vo
# h' y3 v% }( m& y% m% x IPage<UserVo> userVoPage = xUserPage.convert(UserVo::new);% }8 B3 W2 o, C4 }# p1 s) r, ~
if (userVoPage.getRecords().size() > 0) {0 ?! p h/ x2 ~& h8 Z
addDeptNameInfo(userVoPage);
4 u$ R" F. l6 g% V& q& P$ ? }. n2 b7 o) c. p8 T Z7 K
return userVoPage;
5 n6 Q J. f$ e}; z |( i5 m" X; I
</code></pre>
( g' D. m8 I7 P! s# Z<p>查询补充信息</p>
5 S# v. r$ x# |( W<pre><code class="language-java">private void addDeptNameInfo(IPage<UserVo> userVoPage) {! H/ o( M: [1 P1 h! G
// 提取用户userId,方便批量查询" S, g' V. ]+ i1 p0 G
Set<Integer> deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());: b* o6 X- w5 M
// 根据deptId查询deptName
% K7 J& P# F0 k8 b7 J List<Dept> dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
- C0 L& ?& D: k // 构造映射关系,方便匹配deptId与deptName
% N5 i1 G3 t4 @/ l) ~. x Map<Integer, String> hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));3 t; D" S+ n+ R' X/ b: u
// 将查询补充的信息添加到Vo中, J. j# I( z; J2 H! {, V) y
userVoPage.convert(e -> e.setDeptName(hashMap.get(e.getDeptId())));
. C8 J# G. l1 X) J2 c) y} s8 H# d/ ~3 W: ~6 ?& {' I
</code></pre>; R# s4 i+ o* y3 g' j. C
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
# {" L' x9 u8 Y" E+ B<h5 id="2理论分析-2">2、理论分析</h5>+ M$ u; `/ W# k0 t/ l' ^7 g
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p> r5 y( }& K4 w1 g' s7 W
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>: X! W: b4 D# ^: x f) w, @
<h3 id="三一对多查询">三、一对多查询</h3>) r0 C+ P, D" l3 g% ^; B
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
3 K$ v* f. Q# q5 m/ F6 `5 x<h4 id="一查询单条记录-1">(一)查询单条记录</h4>. ?$ M% A9 m7 ]+ I- k; x" f1 |* i9 P, K
<h5 id="1示例代码-3">1、示例代码</h5>
: W/ ]7 f& s/ J2 o: ]<pre><code class="language-java">/**
6 M$ V p8 C* b g3 k+ [3 m" e/ H * 查询单个部门(其中一个部门有多个用户)
3 f( D# Q& Q/ l& C */
9 O& ~0 C2 }! W- u6 F, Y0 ypublic DeptVo getOneDept(Integer deptId) {
3 Q) a! q7 ^ y. @9 A4 X // 查询部门基础信息9 Q& Z, I7 p6 }
LambdaQueryWrapper<Dept> wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
1 _3 t2 Q1 r; E! D4 f) E8 n DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
* q0 g# p- H/ I* G8 o. G( J Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);5 S. |% Y& _3 P
return deptVo;% H* l. R* A6 i2 y
}, Y& F i1 @" J. y
</code></pre>
% K0 l4 l! u, D" ?- X+ v" J U" L<p>补充附加信息</p>% @( I! g5 n( s* j( h
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {2 |# g+ ]6 E: `: o/ s: l
// 根据部门deptId查询学生列表
6 S0 Q- w6 N/ ]3 b. f LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());- @/ q- j" t$ l0 c/ _9 w# {
List<User> users = userMapper.selectList(wrapper);
4 z$ J$ e6 ~4 Z deptVo.setUsers(users);
6 t$ H7 [* m' w: Q9 e}
+ \% b; j; F3 o: {& j- B( o</code></pre>
+ t4 Z& {5 A, Q* p' o<h5 id="2理论分析-3">2、理论分析</h5>
* \. z9 V/ E! Y4 z* w; j. [( O<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>" ]. O6 _9 e6 x% E t' w. R! u! O
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>& B" w8 D" j& D6 Y! D. n
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
; u3 P0 h6 f8 B4 X9 ?( L8 Q<h5 id="1示例代码-4">1、示例代码</h5>9 o" A1 K5 c {5 |: v% i- X6 K7 @" g
<pre><code class="language-java">/**
6 ]; }2 c' s; ^1 B2 B * 查询多个部门(其中一个部门有多个用户)
/ g5 `3 b8 K4 n */
6 e; ~& U/ D% @+ @- E& l7 y' G9 Spublic List<DeptVo> getDeptByList() {
i+ h4 R4 l( I/ o& g. d( x& { // 按条件查询部门信息
C2 N3 ?! |: e List<Dept> deptList = deptMapper.selectList(Wrappers.emptyWrapper());
( u- w* N3 S/ J! S List<DeptVo> deptVos = deptList.stream().map(DeptVo::new).collect(toList());% c2 c' N( E. L
if (deptVos.size() > 0) {# b, s1 k6 L& h+ b* @
addUserInfo(deptVos);
6 [, N/ y7 r8 Y% }% K: r* F0 @+ N }) n& n0 |3 r8 `- h2 R
return deptVos;
3 F: B! W1 R9 x+ k( P& t. i- U5 q}8 { B' c7 L3 o1 ^$ @* }: d- W
</code></pre>; J4 j C/ q! _' }
<p>补充附加信息</p>) J H' |7 H( \' t2 y8 f/ q! ^- s9 t
<pre><code class="language-java">private void addUserInfo(List<DeptVo> deptVos) {) F$ k/ h% Q, R7 _; n% t M8 F t4 f6 y
// 准备deptId方便批量查询用户信息
; j2 W0 ?5 ~9 D' g2 ]0 q Set<Integer> deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
, I# N1 |2 ?: i/ ^2 R // 用批量deptId查询用户信息
$ r8 f9 u( }2 q5 b) w7 o List<User> users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
/ X" W. M) i9 Y3 u- M // 重点:将用户按照deptId分组( e8 W5 Q* o% d4 J/ _
Map<Integer, List<User>> hashMap = users.stream().collect(groupingBy(User::getDeptId));
, z- ~* O; W! \# D0 n! N+ b6 M // 合并结果,构造Vo,添加集合列表
8 }' Z- B6 ~7 S1 m+ n2 }4 _ deptVos.forEach(e -> e.setUsers(hashMap.get(e.getDeptId())));% A3 Y- P' Z8 p& b
}
1 _; l) Z+ v5 p U: h4 L% G: k$ `# `</code></pre>2 O, @# w: A3 c/ `
<h5 id="2理论分析-4">2、理论分析</h5>3 C/ Y- a+ K& S
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
7 t* _, Y8 m- ], x' v; Y# q3 X p% W<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
' ]% m5 R) L, _& x<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
0 z* [* L9 w0 W<h5 id="1示例代码-5">1、示例代码</h5>
* X0 Q4 Q5 f2 K5 L<pre><code class="language-java">/**$ M! z! o/ ^3 T% @
* 分页查询部门信息(其中一个部门有多个用户)9 B- N" [% K3 G. b' M- i
*/
+ \% Y( j `. B Q$ wpublic IPage<DeptVo> getDeptByPage(Page<Dept> page) {
! o( k* M( p5 X' c5 _+ H; E // 按条件查询部门信息9 A1 ~$ x e Z7 J8 h2 V5 S
IPage<Dept> xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());& X6 O* N. Y2 t
IPage<DeptVo> deptVoPage = xDeptPage.convert(DeptVo::new);1 t \. L" j |# y5 y2 \3 l
if (deptVoPage.getRecords().size() > 0) {+ j% `4 V8 X* O6 E4 f/ p! H# h
addUserInfo(deptVoPage);
& o' R1 s0 y' T }9 |/ \6 |. k% |; V( E
return deptVoPage;" e, {: S7 E' v
}6 V8 @( r# U1 c& _. `, S9 K
</code></pre>9 r @' j) z6 O, X4 j4 F/ O
<p>查询补充信息</p>
. Z0 h" W( U( h% v' t6 x5 x8 O<pre><code class="language-java">private void addUserInfo(IPage<DeptVo> deptVoPage) {" q% @- F9 R. v3 x7 s- N
// 准备deptId方便批量查询用户信息
3 Q- U# H6 ^; u; H# S x# G9 A% C Set<Integer> deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
8 L" i K; Y- q& f) G) y2 O LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);$ S% q3 m" m% P5 w/ ^* h
// 用批量deptId查询用户信息
- i% w2 b/ |+ u* N) ? ?$ J' i List<User> users = userMapper.selectList(wrapper);3 E `$ |5 H6 f8 N" u2 K P
// 重点:将用户按照deptId分组
& j( [/ `/ L8 o3 _1 U- R Map<Integer, List<User>> hashMap = users.stream().collect(groupingBy(User::getDeptId));
4 r$ U- m( v/ K9 P1 _ // 合并结果,构造Vo,添加集合列表
- F7 v _ z6 R deptVoPage.convert(e -> e.setUsers(hashMap.get(e.getDeptId())));
% j q. s7 @1 y$ I}0 n4 ~$ q1 a5 f) |0 l
</code></pre>6 |3 V' n/ i, v. e- Z
<h5 id="2理论分析-5">2、理论分析</h5>
- D+ o8 {+ S5 B' L<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
5 S$ ]3 ^" v, Z<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
# P% S: B( K+ w, {% T<h3 id="四多对多查询">四、多对多查询</h3>4 |5 z8 X( V1 k, c. H4 J' i
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>& ^& o% U. c) m7 r
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
5 V/ d: X, l5 L; X+ w<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
) G' J0 F, a i! G4 w* P% k' I4 |1 A<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
: ?3 A; n9 {. k3 x3 a/ z5 E<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
/ W% W: m3 S! q9 T; S. D<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
9 { a n+ d$ ^$ i<h5 id="1示例代码-6">1、示例代码</h5>
7 }7 ]3 n# a# T* J# U+ N- o<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
, l% A7 F' }- f, R4 w" ~0 i) U // 通过主键查询学生信息0 l$ |7 y2 M- b9 x' M
StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
/ B( o, m& j: ] I# k w LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
9 _$ `3 f/ ~4 H/ j // 查询匹配关系
/ X# o9 l \3 u! e G+ V List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);
0 Q% _1 N" S# s& I' ~ Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
. ^" G6 H7 w! k' z2 E! H if (studentVo != null && subIds.size() > 0) {
. A- f5 @4 K: x5 ` List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));/ G! V y' U \+ E
List<SubjectBo> subBoList = ConvertUtils.convertList(subList, SubjectBo::new);+ K! h" t7 H" M2 e. Q% A
HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);
1 a/ H9 V1 l# B subBoList.forEach(e -> e.setScore(table.get(stuId, e.getId())));
# e' e' s; y' e9 G( G studentVo.setSubList(subBoList);7 _# j5 M' ^, h
}
0 u6 V7 P" t' o% Y return studentVo;, j. m. B1 w M3 \0 F6 N
}
7 j' Q2 e p/ R) j' |* H; W/ }' O</code></pre>' y4 J$ d% F1 S, d6 j
<h5 id="2理论分析-6">2、理论分析</h5>5 M) s9 m# @" A1 g
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>4 Y5 g! w" {. J/ K- P
<h4 id="二查询多条记录-2">(二)查询多条记录</h4> v! ]( D- H; m
<h5 id="1示例代码-7">1、示例代码</h5>2 J4 k7 q- T1 F1 c
<pre><code class="language-java">public List<StudentVo> getStudentList() {
# x/ D0 p0 U. r" t // 通过主键查询学生信息& U1 [% I6 W' G9 V8 v
List<StudentVo> studentVoList = ConvertUtils.convertList(list(), StudentVo::new);- ~0 a9 T# P: l: I! ?! n
// 批量查询学生ID
3 m7 I# n( |( T' b( E* c4 Q Set<Integer> stuIds = studentVoList.stream().map(Student::getId).collect(toSet());9 j! f' W+ o% d8 v
LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
+ i/ Z7 k9 r: b* M4 I5 \$ f List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);
& X: b8 C& t! i+ c! J" a& T/ t // 批量查询课程ID# w: F( g0 t- m0 z
Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
& {" q1 I. e& _) W5 Q* h if (stuIds.size() > 0 && subIds.size() > 0) {# ^% J, t2 c+ Z+ i k1 l
HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);
& c) r7 ~0 {$ q: T e List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
' C r }; Q0 `4 g; @/ z, ~1 `8 e2 C List<SubjectBo> subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);2 z, W5 _' H1 s7 d% \' [- d
Map<Integer, List<Integer>> map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList()))); f3 \9 Z2 k7 @, ^0 |# P& L
for (StudentVo studentVo : studentVoList) {
) u& D, o- A# d; u3 a# \ // 获取课程列表
7 D1 q" i+ ?1 z6 H6 G5 r) O List<SubjectBo> list = ListUtils.select(subjectBoList, e -> emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
- V5 a& P- e& V U2 J7 |# @' g // 填充分数# ?: t3 ` i: x) n# j. O
list.forEach(e -> e.setScore(table.get(studentVo.getId(), e.getId())));
; w6 l Y% K$ \3 O0 l+ C% t studentVo.setSubList(list);6 j6 J' H* l0 p4 j, V
}& f4 z9 `6 V$ o' _2 f6 L% D# e! \
}
' i2 m! {# ]6 ?7 b4 z9 l return studentVoList;8 z) C' `% P2 Z9 z, F4 m
}4 m" X1 C# m/ v& {7 z& J+ v, J3 s
</code></pre>
; F, b% j g7 ^/ t+ [<h5 id="2理论分析-7">2、理论分析</h5>% V. e/ X0 f: U! A6 z% |+ o
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>* P' B$ q h9 l- q* N
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>* v, B6 R: m: Y5 s
<h5 id="1示例代码-8">1、示例代码</h5>
' M( A8 N; u2 M. b* e. i+ v9 \<pre><code class="language-java">public IPage<StudentVo> getStudentPage(IPage<Student> page) {3 P1 }+ x5 [* n$ Z0 i! f+ @6 p
// 通过主键查询学生信息
" X0 ^: J+ d5 z3 I6 M/ k& A- U IPage<StudentVo> studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);/ v& U/ q6 k9 r0 @, W
// 批量查询学生ID) q0 ~ A. z `
Set<Integer> stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
7 }; U% n4 K1 D* Z( i2 \2 V LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);4 z3 b% i( d3 m, B; ^
// 通过学生ID查询课程分数6 S0 U5 K3 M& i; o+ p
List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);& Y% m: D) Y0 x
// 批量查询课程ID
( {" ^! Z. g# \: ^. w1 A Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
; z2 T4 X6 K' \* O: Z4 L if (stuIds.size() > 0 && subIds.size() > 0) {
+ j3 M9 O: j1 c" p0 r HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);
) I" x' k6 |) n, O0 H // 学生ID查询课程ID组
* T3 a( G. R/ ] D' h9 b Map<Integer, List<Integer>> map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));& y: n8 }& z5 e3 Q0 q$ q
' y( S" H) s& j, N8 ]; d
List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));6 x- H B5 k X6 h
List<SubjectBo> subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
3 U. t! e# t: ?( w. F/ } for (StudentVo studentVo : studentVoPage.getRecords()) {( y; S1 P' M+ j* l2 z# V# W( h
List<SubjectBo> list = ListUtils.select(subBoList, e -> emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));7 }* z R3 Z9 c& l9 ?
list.forEach(e -> e.setScore(table.get(studentVo.getId(), e.getId())));4 P! O# N$ J8 P
studentVo.setSubList(list);
3 u: q5 v% B- l+ m9 t; d }4 M$ i5 W G2 b
}& ~' {4 t/ j2 y3 V+ \, |2 N
return studentVoPage;
: L5 S7 P: M. R/ @ r/ H}
% t- {/ x3 |* M8 [. c' J0 V</code></pre>
t" d5 N* f& X$ M/ d+ _+ ^<h5 id="2理论分析-8">2、理论分析</h5>
9 V' j* ~. f* B6 ^- y% y<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>' E9 ^) ]: p9 N. x
<h3 id="五总结与拓展">五、总结与拓展</h3>
( f0 E, i# x& H, u+ F% H<h4 id="一总结">(一)总结</h4>" Q7 X r; r$ P I* a* T; ~* C
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
7 V& K% _8 G* J. C2 v' P: \% [* Z<ul>
8 A" A/ d( Y- ]5 }0 K9 \4 R<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>: c4 z7 r2 p$ N* B& _
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>5 V& ]9 X* f0 B j$ H1 {
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>8 L: p w0 [5 Z+ [
</ul>
8 i, y& y. a( k3 _# b<h4 id="二拓展">(二)拓展</h4>- m% u8 ?- [: t1 A0 h
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
: T. Y/ z5 I: O<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>; s$ A! {; v! [4 \9 O* Q
<ul>
3 H: |* ~' P. D& t+ {0 [<li>当数据量较大时,仍然具有稳定的查询效率</li>$ I: `& w5 Q* E; y
</ul>+ t( S& c' d: H
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>2 U3 U, v E9 W
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
* K+ b! J6 Z j- e3 a<ul>$ x, i O, X! N3 I, X
<li>与二级缓存配合使用进一步提高查询效率</li>
6 D. u# W, F! M/ z</ul>
. a" N, w5 {5 x9 Z& ?$ n<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
$ T1 ]0 Q7 ]: I6 C' u+ }<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
& `" l* }0 J7 a6 r& W+ U, S
0 o: j+ R! Y, W/ T0 n, i |
|