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