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