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