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