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