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