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