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