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