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