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