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