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