|
|
4 O0 S+ ~% w: [1 p; E" E/ | [( e<h3 id="一序言">一、序言</h3>" Z2 p6 C; u% G/ p- D; J
<h4 id="一背景内容">(一)背景内容</h4>
- ]. s ^1 S! F/ F* W# u$ j<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
9 Z) K! B6 ?; g) {5 |, d- C<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>0 v- ]; d( @# I9 k! H! Z8 q4 e
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p># q! a* F! i/ S9 i7 i
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>8 y4 W7 x# |& `6 F: D
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
# d) ~# }3 S" @* \' ~# Z<h4 id="二场景说明">(二)场景说明</h4>5 f; ~9 p: Y; F" N2 L* Z
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
8 v! V' Z1 M3 b" e" u<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
, O) G# V3 _) N+ E( J5 r- T I<h4 id="三前期准备">(三)前期准备</h4>
4 {9 |; v N3 b: f6 H<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>7 V4 g" x% Y; z8 |" d
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
, f/ q7 m" ~, q0 W( G8 R* w<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>& _' H) H" F9 L# }
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>1 y9 J) d; g9 x* ?& X* A& B) g7 k7 [
<h3 id="二一对一查询">二、一对一查询</h3>
" A$ V8 B: y6 u5 B4 w7 h<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>- ~! {) I: M, A6 n m9 ^* Y
<h4 id="一查询单条记录">(一)查询单条记录</h4>" z; X- D# a1 c
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>1 R( K0 ^# |' F- c" M7 c
<h5 id="1示例代码">1、示例代码</h5>
/ \% s. k, `7 ^7 n<pre><code class="language-java">/**
* r; a; k3 f6 y9 n * 查询单个学生信息(一个学生对应一个部门)
7 r% P: N5 D' j0 b1 R; U */
5 V+ L1 x" r9 S$ V# w$ W' ^( spublic UserVo getOneUser(Integer userId) {! V0 }$ W5 J/ m7 u( X) ]$ ^! s
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class)
# g. V" i$ A' }5 n/ }2 q .eq(User::getUserId, userId);
* c6 L$ |. ^0 S // 先查询用户信息 S" \1 B+ p2 y8 i8 d
User user = userMapper.selectOne(wrapper);
9 H$ X `6 q& e, E- X // 转化为Vo- p! N' q! s" V7 B
UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);7 y& _' W/ L9 Q+ t8 v7 Y* r6 w
// 从其它表查询信息再封装到Vo
8 q( J! s9 P- _ Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
2 K E4 `& s9 l! f' o; r return userVo;4 G- S5 p N" K( ^, w
}
6 s/ r9 H* _7 ~* m2 M</code></pre>/ Q% m! _ U& _8 j/ n2 d6 V6 D, M
<p>附属表信息补充</p>
* h9 I P% P6 K( \4 e4 v& S/ N' T<pre><code class="language-java">/**9 N' w% g. ?! ~3 O
* 补充部门名称信息
& P4 b# \6 A; p$ B. u */3 G& S, K& m5 |# D/ P9 ?
private void addDetpNameInfo(UserVo userVo) {
: E4 O0 p6 b. Q LambdaQueryWrapper<Dept> wrapper = Wrappers.lambdaQuery(Dept.class)! r9 i! W, i' k, m; @' i
.eq(Dept::getDeptId, userVo.getDeptId());
" r) y' ?! ` I. v" Q+ L& o* o* n Dept dept = deptMapper.selectOne(wrapper);
3 g5 Z! y+ G2 S1 j Optional.ofNullable(dept).ifPresent(e -> userVo.setDeptName(e.getDeptName()));
# A& \9 K1 @& B; @- C: L/ g}$ H0 o' E$ [- ]5 m) e; u, V
</code></pre>
& D( {/ u. z: h# W6 X! U<h5 id="2理论分析">2、理论分析</h5>* W# k/ \1 \& y- W
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>6 h6 O% w+ n+ I' G; a) \6 K
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
. Z" D* J. s7 F' G<h4 id="二查询多条记录">(二)查询多条记录</h4>6 J' P: V" y% r1 e6 f( k0 D# U) r
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>) w7 T7 y) U, x% { Y! \; [
<h5 id="1示例代码-1">1、示例代码</h5>
6 W) C% B# G* V* x) U3 d7 a<pre><code class="language-java">/**4 \ |, l5 M4 W8 F1 ^
* 批量查询学生信息(一个学生对应一个部门)
5 J: N4 m5 ?+ Q */- K4 r+ o# Q- a" k% w: U; i3 q7 w+ T
public List<UserVo> getUserByList() {0 H2 z9 d# E2 i" H5 _: H5 F
// 先查询用户信息(表现形式为列表)! N$ ~- j9 f" a$ h5 I! m& N
List<User> user = userMapper.selectList(Wrappers.emptyWrapper());
* C. `- a& c1 m8 n4 M+ P9 r List<UserVo> userVos = user.stream().map(UserVo::new).collect(toList());
n d/ `. f2 b( k7 l // 此步骤可以有多个# l9 U) C# }1 A
addDeptNameInfo(userVos);
} }, c; u. K return userVos;
+ z- {1 `& W1 H$ {9 _0 J" k' K}% s2 l2 H; I( V3 L2 |
</code></pre>. x8 G3 ~% ^9 c7 S
<p>附属信息补充</p>
: @8 f7 S! `5 t<pre><code class="language-java">private void addDeptNameInfo(List<UserVo> userVos) {
4 X/ |! U0 e W; x2 z // 提取用户userId,方便批量查询
1 V7 H! X5 X9 J! b% C' M5 t" ~* f4 t Set<Integer> deptIds = userVos.stream().map(User::getDeptId).collect(toSet());* L) L/ s) \- r- q0 O2 f. ^
// 根据deptId查询deptName(查询前,先做非空判断)
. j, @$ o& R" N( o) j% Z$ a, i5 C) c List<Dept> dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
6 `) i9 F3 c2 t9 Y; @ x7 l // 构造映射关系,方便匹配deptId与deptName) P* r+ T2 q8 j( o, I9 I; ?* x# ~5 b
Map<Integer, String> hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
9 ^3 K" k7 q# D // 封装Vo,并添加到集合中(关键内容)
F1 O: L4 p+ v+ M, F4 ~% _% z userVos.forEach(e -> e.setDeptName(hashMap.get(e.getDeptId())));) | {+ Z/ w2 z7 z
}
9 E( @' R2 q2 t6 N, a% X</code></pre>" B' Y) U% n2 O. j/ H' n- X
<h5 id="2理论分析-1">2、理论分析</h5>
4 V3 @: k. _# k4 W0 z<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>( H9 C. n2 w$ _+ y6 ]: H
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
! o4 { v$ `) @<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
& S- q# i: Z" S+ i<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>5 f5 O0 S4 ` A$ l j o
<h5 id="1示例代码-2">1、示例代码</h5>9 }9 \1 m. z$ l1 ~5 e
<pre><code class="language-java">/**
i" p2 T( U; G# ]0 U6 L, Q% F * 分页查询学生信息(一个学生对应一个部门)
# g; w: W) @ B' Y */7 X$ O# S( K: W7 T3 d& V
public IPage<UserVo> getUserByPage(Page<User> page) {7 ]2 w* P; _* I1 d# ]
// 先查询用户信息9 y: K/ N$ f7 Z \' b
IPage<User> xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());" |) j$ K$ l$ G5 ]0 y
// 初始化Vo
2 M2 E9 B3 S4 m- L IPage<UserVo> userVoPage = xUserPage.convert(UserVo::new);$ v3 @/ }1 p! i! B
if (userVoPage.getRecords().size() > 0) {
0 _% j! P: [6 O. e" [& i8 _- w addDeptNameInfo(userVoPage);: W1 M' o1 O" q& z# m( t% \. R& ?- J
}6 X; ~1 P1 W- F' n& ]& V! ~% G
return userVoPage;
% a5 m# I5 ?! [% G}0 P3 o. r9 e. u! I# ?# n! Y g
</code></pre>2 O$ @6 e0 A. s m
<p>查询补充信息</p>: p: T3 h0 } ?& D
<pre><code class="language-java">private void addDeptNameInfo(IPage<UserVo> userVoPage) {
' a2 a& u9 r& j2 ? // 提取用户userId,方便批量查询& @$ m, P/ Q$ ?4 H' j
Set<Integer> deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());: e' q9 u+ X* }8 B, ]$ V
// 根据deptId查询deptName; f1 {# R6 e) @5 t9 C" o
List<Dept> dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));# B7 v( F0 i% R# e
// 构造映射关系,方便匹配deptId与deptName
9 a; m& ?/ I6 ?% N7 o: s Map<Integer, String> hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));$ K8 t4 t& ]. |. \( B# d
// 将查询补充的信息添加到Vo中
9 V( V( I3 q+ R N5 k7 L/ ? userVoPage.convert(e -> e.setDeptName(hashMap.get(e.getDeptId())));( j; P6 H/ ]) p1 |, p2 ?
}# K6 V% r6 T8 o4 T
</code></pre>
& k$ X! {: ?# }9 \$ }# h8 Q6 b<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
k$ ^) W. M( ^% ~8 z: @<h5 id="2理论分析-2">2、理论分析</h5>
7 ^' W e# O: y+ c" ~1 {<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
1 {* M0 ]5 w, N M8 w1 i<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
" B1 @' `# i! q0 r/ s) E5 \6 O<h3 id="三一对多查询">三、一对多查询</h3>
) z( M' I3 p/ E0 |3 N2 N<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p># B' z' G" a; R9 Q
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>% I: [5 {) P0 {6 k' h) A
<h5 id="1示例代码-3">1、示例代码</h5>- M# `1 D3 S) o! V7 V0 Z" ~
<pre><code class="language-java">/**; {, B( e; W$ ]4 R
* 查询单个部门(其中一个部门有多个用户)
. P: a" ^. Q! \% y" \& H7 ~3 d" U */
9 c; A v) ~+ G& Wpublic DeptVo getOneDept(Integer deptId) {
9 n" ]+ S9 `2 u+ \: W" C // 查询部门基础信息
3 X% N; R5 S9 v5 {( d& H6 F; k LambdaQueryWrapper<Dept> wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
2 _ R3 |8 e, X# `( ^# B DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);- R3 U5 i* L: ~4 c4 F
Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
3 U4 M, K" m" o, @$ Z return deptVo;
3 Q* k; B$ s+ s}
& v# y9 W; h; w8 b" w* S</code></pre>
! Z$ B' ?7 d/ |7 L<p>补充附加信息</p>8 {7 T) P% C( z# ~6 U' Q
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {" y3 z, [" d d: Q L
// 根据部门deptId查询学生列表
$ Y+ y6 p# l- z LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());6 @* }& ^; s5 R7 M% X
List<User> users = userMapper.selectList(wrapper);. g7 }2 }6 k, X
deptVo.setUsers(users);4 [8 e9 m; M8 f" L9 Q$ O
}
' p' o- p/ |* ~5 X( w" t) o</code></pre>
0 t O- `7 `! b- v1 m8 U: b<h5 id="2理论分析-3">2、理论分析</h5>
/ _0 X& n4 Y, x9 o/ a! l<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
/ G% h% G. B3 `7 h<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
8 u$ j2 v. Z \2 o8 T! O<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
, H- V5 z# F2 O+ M" o6 N' M<h5 id="1示例代码-4">1、示例代码</h5>' \+ B7 w4 ^5 o2 X( c0 p
<pre><code class="language-java">/**
0 }' C+ H; _5 `) [* K. j, Y * 查询多个部门(其中一个部门有多个用户)! C8 l* p) ?. {! q( T
*/
: `# z3 R& Z! _/ s3 e1 }public List<DeptVo> getDeptByList() {8 h. w, t9 ` q5 O. n( \
// 按条件查询部门信息7 ^# p. S- h9 f2 u3 R2 { ^) T) R
List<Dept> deptList = deptMapper.selectList(Wrappers.emptyWrapper());
6 k0 [4 \5 q* ~1 R" ?% k List<DeptVo> deptVos = deptList.stream().map(DeptVo::new).collect(toList());
' `2 D) \* ^! U8 m8 ^+ |+ _ if (deptVos.size() > 0) {4 d; W/ y& v( M) Y/ s
addUserInfo(deptVos);9 k, M2 f' b* Q& Q! ^! ]% P: `: m
}# }. z& _7 f2 _9 Q* h* k& M
return deptVos;
z- o) I. H; y8 o}
W& G- W) a/ T& e+ f0 k</code></pre>
3 K* a0 ]. Q# R# `! C<p>补充附加信息</p>4 f+ [3 t- M& p! ~7 a6 }1 {
<pre><code class="language-java">private void addUserInfo(List<DeptVo> deptVos) {8 K. t" @; Y- K5 m* u
// 准备deptId方便批量查询用户信息1 Y) c r- U! n8 @' x# t' m
Set<Integer> deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());( Q+ O3 C( @3 Y
// 用批量deptId查询用户信息
9 V1 |3 _) L( B) m3 H8 H! u List<User> users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
0 U, L# R" R- F" L' c, O // 重点:将用户按照deptId分组
( j! D* J' k( Z3 n9 I( J5 ?) y Map<Integer, List<User>> hashMap = users.stream().collect(groupingBy(User::getDeptId));
9 s% E2 ?- P) O g4 j7 l // 合并结果,构造Vo,添加集合列表' K; {' L% t6 c7 K9 Z) l2 y
deptVos.forEach(e -> e.setUsers(hashMap.get(e.getDeptId())));
' h! t( z- W& d7 z}1 }& q2 \* d* g, {) D
</code></pre>$ h% T6 |' n0 M8 X3 y1 @
<h5 id="2理论分析-4">2、理论分析</h5>/ T, K$ ?2 T5 O/ r' b
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>+ r1 A( C& N& A
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>* {7 g) b" w3 j8 o& d7 ~
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>, G. _& W: z4 Y7 O
<h5 id="1示例代码-5">1、示例代码</h5>. a1 k" c* S R
<pre><code class="language-java">/**
1 _! L* Z; V1 s7 e o" j, D * 分页查询部门信息(其中一个部门有多个用户)
1 {& D3 O" ~% e& A3 S */
1 h' n- p! ~9 J# A6 j( H2 vpublic IPage<DeptVo> getDeptByPage(Page<Dept> page) {# P- k* K; m1 I; y# n
// 按条件查询部门信息
: E. P- ]1 A! N2 ]* ~% n IPage<Dept> xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
* J: G4 ~8 m. G6 P* Y+ H: {: D IPage<DeptVo> deptVoPage = xDeptPage.convert(DeptVo::new);! p. y- f9 w5 J: f* w: f% u% Y
if (deptVoPage.getRecords().size() > 0) {6 x% q7 C& e' I; v/ ]" `$ w
addUserInfo(deptVoPage);" v# X) ^. M1 z! i5 w( Q! B4 b
}
7 Q: p- X5 D+ o2 H% p3 s4 P/ C return deptVoPage;
. n; e3 h# x- T. t8 @5 _}
+ a4 {3 ]9 {! Y; Z+ l</code></pre>1 l1 D, J9 O0 R _ G; g
<p>查询补充信息</p>1 [/ p9 k8 x& R2 b, j; o+ p
<pre><code class="language-java">private void addUserInfo(IPage<DeptVo> deptVoPage) { Z& Y) b* g1 ?1 E* O
// 准备deptId方便批量查询用户信息
3 N) ]2 H2 j: h, i' N2 L6 e3 l Set<Integer> deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
7 F! {" b5 ^0 y# V8 G+ x0 m4 } LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
, P- d' w' J2 I! o // 用批量deptId查询用户信息5 E0 r, b% n5 q- {. r" _' _' B5 B
List<User> users = userMapper.selectList(wrapper);. t+ o O4 P2 q/ }; i( T; u7 }
// 重点:将用户按照deptId分组
' Q. A+ X# i; W( f. T Map<Integer, List<User>> hashMap = users.stream().collect(groupingBy(User::getDeptId));/ Y6 b0 b1 [, ^6 [& W2 V! L
// 合并结果,构造Vo,添加集合列表. N% u0 H! M1 u$ [
deptVoPage.convert(e -> e.setUsers(hashMap.get(e.getDeptId())));; s! _9 Y" j8 f8 M: S3 k' x2 Q) e8 E
}. O! {! V8 j" v: Y" M
</code></pre>
; e+ y/ y2 p- B$ A) ~<h5 id="2理论分析-5">2、理论分析</h5>
$ s1 A/ [, H$ w- t% i/ n; ^( B; k<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
9 ^+ ?. y* d2 Z4 R5 Z+ w<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
" `- W; ?3 R4 i- k<h3 id="四多对多查询">四、多对多查询</h3>0 L0 `8 G6 K) L
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
, ^: `3 s2 O, x' ?0 U4 K* c j<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>7 y. s- h: z0 b& p
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
- u- W, q! y# [/ a" X3 [1 g2 p) X! ~' {<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >; u5 x2 d, |8 r& L* v( q* F2 g
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
7 U& Q# G+ c9 {& c<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
- i- I8 a: m4 S9 Q<h5 id="1示例代码-6">1、示例代码</h5>" ]5 |$ _ B: d( n/ X1 W7 B9 j
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {$ a' E2 M$ y$ R2 h3 Z+ V
// 通过主键查询学生信息5 x, T& L7 H7 W: N
StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
" U* ?9 N% C" Q; ?# Y2 l5 ^ LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);7 W8 ]. @7 _& q, v, a( [
// 查询匹配关系: L8 i( g9 Y# P+ H5 T
List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper); V5 y2 E* H7 O/ n
Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());$ C/ I @. G" d# k+ E
if (studentVo != null && subIds.size() > 0) {5 g) W5 S2 z5 k
List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
. L: C/ P: t: i. s. @ List<SubjectBo> subBoList = ConvertUtils.convertList(subList, SubjectBo::new);' T' W% P, ~$ x, f( E+ }" }0 s
HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);/ W, |9 R6 p, U* @: m
subBoList.forEach(e -> e.setScore(table.get(stuId, e.getId())));( t8 e5 E) q, T
studentVo.setSubList(subBoList);
7 p! [0 q d$ I }
# \4 r w4 X/ P3 n return studentVo;. K' F/ j5 d* K3 i
}) X2 G$ a( u$ v, e9 K5 p" s
</code></pre>: `3 |5 ]' o1 v" @
<h5 id="2理论分析-6">2、理论分析</h5>
: ^* L0 V9 l0 x<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>) X/ r- ?5 p$ w) x
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
1 z7 z) y) n, }% B<h5 id="1示例代码-7">1、示例代码</h5>
: f5 U( Q! a- Y q: ?5 Y<pre><code class="language-java">public List<StudentVo> getStudentList() {& B r/ O) ^0 j9 _ o% _% o2 e
// 通过主键查询学生信息
: L) s4 i( c8 g- F$ } List<StudentVo> studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
0 X- [. H6 z+ O; C- g& J // 批量查询学生ID
/ I8 _; D: B {- l% z, E+ u Set<Integer> stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
9 d+ Z% l {7 N- \5 @( D LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);9 F! m3 I. `& V) n
List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);
+ B; j- ^5 O3 w. ?. j6 B // 批量查询课程ID- h' y4 f) p9 f# [$ v Y) W
Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());9 K5 x' J9 W. f j- C
if (stuIds.size() > 0 && subIds.size() > 0) {& N5 J- U0 [& }7 }/ @& T
HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);
7 [6 Y# s2 e5 B# Y8 g8 g7 i% h6 | List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
: l" o1 | m, P7 R% r* O List<SubjectBo> subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);* `! T9 ^( E8 l( y
Map<Integer, List<Integer>> map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));$ g/ c' [/ i) n- [$ K( o' F
for (StudentVo studentVo : studentVoList) {
4 b- A% V: g) |6 u- n! _ // 获取课程列表6 T/ m, |/ Y* v+ h
List<SubjectBo> list = ListUtils.select(subjectBoList, e -> emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
% l, x, R8 H6 w- @# p // 填充分数
$ I! C' J" ]+ {* S3 r list.forEach(e -> e.setScore(table.get(studentVo.getId(), e.getId())));
1 A: H w& K6 ?, Y: t8 P' M) ^ studentVo.setSubList(list);6 [3 w) N7 l1 P5 x% [) ]- Y1 y% g) K
}, p" [7 i% j# g0 H" k' ~
}7 J( Z i# X8 I4 N5 Y8 _ x6 C6 d
return studentVoList;# p; ~% Q; _& R
}
8 [9 x J* f2 F( C</code></pre>! u- ?3 j S5 R5 G9 a) C, H
<h5 id="2理论分析-7">2、理论分析</h5>
5 v4 B n& j# f* v0 i! D) i<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
1 f) p& D$ Y. A" g, ]<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>$ [5 I! t6 B1 ^7 V; y+ F
<h5 id="1示例代码-8">1、示例代码</h5>
/ v7 U- P, L: W) X. a<pre><code class="language-java">public IPage<StudentVo> getStudentPage(IPage<Student> page) {7 x, W* q/ u' [# a$ T) Y
// 通过主键查询学生信息- y! I, f! u8 x4 `5 b" g) V
IPage<StudentVo> studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);) N" P* f$ T: h# B7 _1 H
// 批量查询学生ID9 v! V% H5 b; C: G: L
Set<Integer> stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
" v [4 T! W: @2 O- m" w2 |( [1 ?8 r LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
: Z5 Y8 G$ x2 Q/ ^ // 通过学生ID查询课程分数- l( Q( a3 Q+ L/ C. O+ G
List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);
5 z3 N8 g- b4 R+ ]+ O4 Z/ j) u" c // 批量查询课程ID) K8 K: m3 D! Q3 v
Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());& N3 n( [, I- Y9 D( n
if (stuIds.size() > 0 && subIds.size() > 0) {
+ J0 N& B8 B. C HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);1 E" s4 S- A+ a
// 学生ID查询课程ID组
, |$ c+ V2 Z! T5 s7 I Map<Integer, List<Integer>> map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));, C& h+ t% Y% G( c8 {
6 X" t; b6 G9 F- \3 O$ Z( p List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
1 k n9 H+ T* {9 ?2 y7 _/ W List<SubjectBo> subBoList = ConvertUtils.convertList(subList, SubjectBo::new);8 Z1 _7 i5 A m( U
for (StudentVo studentVo : studentVoPage.getRecords()) {
, r4 Z( b$ b) U- w List<SubjectBo> list = ListUtils.select(subBoList, e -> emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));5 {- E) [3 Q3 H( l- q
list.forEach(e -> e.setScore(table.get(studentVo.getId(), e.getId())));% y4 l# Z' ~5 ]+ l7 P
studentVo.setSubList(list);6 d) K9 |3 U& G' y5 H6 l
}! P% ?% \# t7 u/ k; m( W9 r1 s
}
9 D) W' W5 p& k. ]& a' g% O return studentVoPage;4 [- `9 c; I" a1 B- z8 S
}
5 Y" [' B6 P, Y( y, I) J</code></pre>3 O: n. I0 N& _) y& N' @
<h5 id="2理论分析-8">2、理论分析</h5>, t, A# d; L/ v; Y# R5 S1 u
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>9 L- u! ^% j. S2 l- y
<h3 id="五总结与拓展">五、总结与拓展</h3>. H! V; ~8 C$ V
<h4 id="一总结">(一)总结</h4>0 R& p7 C% d! E* o! A& J6 i
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p> t" g) Z: Q; P2 } s+ M l
<ul>% Q7 T/ v. D# f6 K, b4 A* U8 w! M( m
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>$ s Z- M% @) c, x- s- w
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>* i' ]/ l4 G) Y$ c' \! g6 X
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>; b; L' g5 T2 f0 i
</ul>7 u, I1 v" w* X# a$ r+ p& f8 p! m
<h4 id="二拓展">(二)拓展</h4>+ ?8 o- X; c. l0 r$ W- C
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
9 j1 o( `5 @. `1 R9 b w<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>" q* l# C$ v! L& F
<ul>
" p* |, ]" c4 y! }8 J<li>当数据量较大时,仍然具有稳定的查询效率</li>
% e: _9 R! w% D# {& V( U6 [</ul>3 j+ m/ X# W. [0 T7 z
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>/ P6 a4 f! P! b/ S" {
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
& H( g* \- h8 _ f! ^! ?! r+ @- x<ul>7 t8 Z0 s6 i; ?
<li>与二级缓存配合使用进一步提高查询效率</li>
& L e4 n, j# q( Y) J</ul>
4 {! P" G- E0 {# y F( K<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
( O5 S) l9 V; s. [; C8 C) s<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
; t, H5 ?: ^& u, G) j, V7 }* Y( c* f
|
|