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