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