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