|
7 [+ e! m/ U% e4 {- t- G8 X( V
<h3 id="一序言">一、序言</h3>0 |3 W- z4 e- Y5 p: R4 Q9 m
<h4 id="一背景内容">(一)背景内容</h4>9 ^% s* \. ^5 V! d& }0 o
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>% Q" V& K% [* K& E3 x
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
5 A+ Z, O1 ? j; J" A. u( |<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
$ X" u; U2 J. R0 a<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
0 a% U; d9 d" K9 n' L, \<img src="https://www.altitude.xin/typora/image-20211021114957682.png" > n( ^/ i* \8 n3 u. i& k" b5 d3 B* N
<h4 id="二场景说明">(二)场景说明</h4># x. r$ Z$ x( G7 k G+ X0 e
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>. k7 F$ C" y1 U4 y% F# @
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >& i# M: v7 d0 p
<h4 id="三前期准备">(三)前期准备</h4>
; w. Q4 K( T1 e8 S! A0 M6 P& `- I8 p<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>1 K$ |- h( S+ j& [
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
' K: a- X' Q+ l<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
R1 p$ l/ r& K3 _! p/ h3 a<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
& |+ ?. ^" \/ Y. p4 D c<h3 id="二一对一查询">二、一对一查询</h3>
7 S, w5 C" D/ `( N: n& I! H<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
% ]2 U, s: ^( G! H<h4 id="一查询单条记录">(一)查询单条记录</h4>
( F6 c9 O j9 M; q<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
& A9 h& {( x2 U4 Y. O; b<h5 id="1示例代码">1、示例代码</h5>' }0 Q% X U1 Z- H8 K, q6 j; R
<pre><code class="language-java">/**
[2 s t" l' T- N * 查询单个学生信息(一个学生对应一个部门)8 ~1 T9 s/ }4 ^8 w: `+ J, X1 g# y
*/
5 L3 q1 X' z3 c7 K% ]public UserVo getOneUser(Integer userId) {0 v7 N1 l% R/ P9 @) ?
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class)6 J( Q, b" T% A! U/ T2 i
.eq(User::getUserId, userId);; G+ y) p! w+ O) u6 z! H
// 先查询用户信息
; M a. D/ t' U; b; A User user = userMapper.selectOne(wrapper);
" ?) S: ?" o/ ~, T* f) I // 转化为Vo) @/ s2 V: N+ C' M. F3 p
UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
: J ^) j" I' v6 c6 E // 从其它表查询信息再封装到Vo4 v) o9 }' i* D% f0 i, x# u* I! C
Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);3 m, @2 a2 L. [# N
return userVo;
5 O% Z0 z# c. z& @5 j}
+ ~* T/ O' k; w# D</code></pre>
: M* P; u& L" w& F<p>附属表信息补充</p>7 _( L* z1 C$ r/ u ? [- F1 q
<pre><code class="language-java">/**1 L$ c2 ^) F/ T) s8 J) ]% {3 s
* 补充部门名称信息
$ c' x) a; q/ R */5 A% p+ c4 l. `3 j
private void addDetpNameInfo(UserVo userVo) {5 y: v! T7 `. s* e4 C: T5 z' X
LambdaQueryWrapper<Dept> wrapper = Wrappers.lambdaQuery(Dept.class)
2 l4 U$ S% `1 Y% [ .eq(Dept::getDeptId, userVo.getDeptId()); \: A+ @- N1 }* a; l2 j! x
Dept dept = deptMapper.selectOne(wrapper);
' M- G J5 u! c4 S3 e Optional.ofNullable(dept).ifPresent(e -> userVo.setDeptName(e.getDeptName()));$ J, s/ w: W; s8 Y: P" j
}* ^$ {9 N6 u ^0 i# {
</code></pre>
! Z4 t+ x4 [, a% R, q<h5 id="2理论分析">2、理论分析</h5>
8 |: q ^# ~( R' u<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
/ P1 [, ]% k* t9 r7 B% V<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
) y0 W3 ^ C( l7 }/ w' m6 I+ W# B<h4 id="二查询多条记录">(二)查询多条记录</h4>0 E! x' [. z6 ?9 f
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>9 D, M* @1 b" p" Z
<h5 id="1示例代码-1">1、示例代码</h5>8 f# P. w0 u6 \; A3 t
<pre><code class="language-java">/**
' o$ g4 k7 P F7 n- e * 批量查询学生信息(一个学生对应一个部门). x/ f; p5 R3 S/ \8 f
*/
: O+ }/ ` H6 q; v0 Q4 f( o0 jpublic List<UserVo> getUserByList() {( T& m! Y9 W' c0 O: a4 s" X
// 先查询用户信息(表现形式为列表)
$ z, @, z9 d! M- D8 x List<User> user = userMapper.selectList(Wrappers.emptyWrapper());
! _9 } q1 s# S, e8 l& ?0 \' e List<UserVo> userVos = user.stream().map(UserVo::new).collect(toList());' \( U) h6 \, x$ i; @. u3 m
// 此步骤可以有多个) |" b4 x7 a& F) {0 `! o
addDeptNameInfo(userVos);) j5 P. R! a* U
return userVos;
+ U% }: Q" Q' o6 `. ]+ o}( k1 _! W- E% l7 p
</code></pre>
0 ]8 U" Z3 R; d4 v8 K: P<p>附属信息补充</p>$ X+ Y& |- f4 Y; n; i
<pre><code class="language-java">private void addDeptNameInfo(List<UserVo> userVos) {5 ~" ?- n: {) }( u1 [
// 提取用户userId,方便批量查询4 E, I* u- @. t0 h& G
Set<Integer> deptIds = userVos.stream().map(User::getDeptId).collect(toSet());3 K0 G0 d9 v0 d3 C; S1 n
// 根据deptId查询deptName(查询前,先做非空判断)3 ]& p8 t8 I ~
List<Dept> dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
* ^% J6 H0 q) |- L# p // 构造映射关系,方便匹配deptId与deptName
" M4 W4 l3 t/ ] Map<Integer, String> hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
4 c! M! l7 O/ ^1 W // 封装Vo,并添加到集合中(关键内容)4 N# U/ \: d7 b: O4 _: F/ z
userVos.forEach(e -> e.setDeptName(hashMap.get(e.getDeptId())));
- L1 v4 B' U9 B$ R* n& }8 u" @% H}4 O& u- y$ ?9 l. q9 x7 v
</code></pre>) L A1 s! V% [
<h5 id="2理论分析-1">2、理论分析</h5>
1 D6 r5 P& K2 w) P4 w9 d2 m<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
) y" T5 k1 n7 A+ H6 l9 O<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
y7 T# M& R% |, ?, X: r<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
; Z9 }7 b9 a: I- ~<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>; x | v, M9 h
<h5 id="1示例代码-2">1、示例代码</h5>* t- k+ y* V- |: \+ @3 U
<pre><code class="language-java">/**1 Y& z, r2 z' N/ c+ `7 ^% d
* 分页查询学生信息(一个学生对应一个部门)
1 L! }& R" u: w* c/ |# T5 h5 p */
/ i* P* X3 V3 A' Dpublic IPage<UserVo> getUserByPage(Page<User> page) {1 R9 } N* Q$ b$ W
// 先查询用户信息; x7 Y8 s- U' N4 E+ @# Q
IPage<User> xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());) Z* ~) d7 i/ q/ r7 w( e! {7 C
// 初始化Vo9 P' P% T2 t) J0 t. z$ v$ d
IPage<UserVo> userVoPage = xUserPage.convert(UserVo::new);1 Q7 t' X% [! ~, u; d9 `
if (userVoPage.getRecords().size() > 0) {
3 }! F* |- i8 e5 t3 N0 t* O' B( ` addDeptNameInfo(userVoPage);
5 Y' e: Y w9 o7 ~+ I: ]! i% i' | }
) S( I* Q' y3 S9 e9 p( \6 J) h return userVoPage;
$ I' l' H% f# d4 H( ?6 q- L; ~0 e* [}2 w0 I. t) _4 \1 D. m8 _
</code></pre># R4 {! i1 y& y" E( ?
<p>查询补充信息</p>: J/ x/ _/ S* v5 Y* I
<pre><code class="language-java">private void addDeptNameInfo(IPage<UserVo> userVoPage) {. P+ N+ B( v4 F! g1 w( w
// 提取用户userId,方便批量查询
3 n) Y, [' j6 S6 x1 A# j Set<Integer> deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
1 Y3 o5 f- `% ?; W& p$ { // 根据deptId查询deptName8 y D. j& Z1 ]
List<Dept> dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
# m7 g5 g! q* F0 U G+ i3 y/ j // 构造映射关系,方便匹配deptId与deptName3 E+ \% Z; d _& l: w" B
Map<Integer, String> hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));! V3 o* H$ @% v4 H& e+ ^, L, N
// 将查询补充的信息添加到Vo中0 x0 \7 Y. T& ?& D% _$ A9 S/ v
userVoPage.convert(e -> e.setDeptName(hashMap.get(e.getDeptId())));/ f! O. W2 Y# |6 i0 B2 `4 ` r6 i
}
6 P0 Z, P! ^3 Q1 `* U0 o( e</code></pre>
7 I( \9 A: q2 \/ c* p<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
9 Q2 P: v! c( i X9 H<h5 id="2理论分析-2">2、理论分析</h5>$ ^. v+ e! D4 M5 K* _# K1 m0 Q1 k! q) r
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
8 F. S2 I5 x2 S& A<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
; O! {. j. p9 e) ?$ O, B& t0 R<h3 id="三一对多查询">三、一对多查询</h3>/ h; @6 X5 R$ f* o0 @
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>; G+ S) `5 I8 o
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>0 \" Y# T0 L0 Q9 m+ r6 I* m, q
<h5 id="1示例代码-3">1、示例代码</h5>
m# F: T8 n! U' E. b' _<pre><code class="language-java">/**3 t& ]% b7 g$ _7 ?4 {4 ^
* 查询单个部门(其中一个部门有多个用户)
0 J; f5 J, ^9 D0 M7 q */
. H$ n9 O6 {/ ~& W9 b Cpublic DeptVo getOneDept(Integer deptId) {
( h% H/ |& c N // 查询部门基础信息
: x j! l* C6 n. d/ v. n9 w; e v LambdaQueryWrapper<Dept> wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
1 }1 V h+ Y% S9 F DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);+ n9 O- T+ c9 L! J# [
Optional.ofNullable(deptVo).ifPresent(this::addUserInfo); J# X! g8 X Z& M+ C$ ?* q9 C: @
return deptVo; x, R2 v. [- L5 b& }% h. v
}/ v+ r/ [. I4 ?0 l( B/ @
</code></pre>) E" P: I# M u
<p>补充附加信息</p>( ~' J; v/ V; g. A5 ]7 j
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {+ P& r$ K4 h* w; I$ {1 ]! @! `
// 根据部门deptId查询学生列表% ?! [' c0 f+ d- K. f, L f* ^* w& X
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());3 Z9 W1 ?3 Y3 A8 n
List<User> users = userMapper.selectList(wrapper);
: Y& l' w% D! o+ S deptVo.setUsers(users);6 g. _( R# |+ V9 G. }/ J+ J8 f
}5 v7 t5 x( U, d2 C6 o
</code></pre>. O, `1 B* O: y9 r( m7 N- X
<h5 id="2理论分析-3">2、理论分析</h5>
/ c l# E6 M4 d) |! [<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>" \- x- [8 t' X( |" a( v0 T
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>- ]5 B2 T3 G$ I
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
3 K" z( ?# t- u( C. l" N8 B<h5 id="1示例代码-4">1、示例代码</h5>
; I$ d9 `3 [ u2 T) M/ D7 l<pre><code class="language-java">/**8 |( L# ~( X! J; d# e( B! ?" D
* 查询多个部门(其中一个部门有多个用户)
9 h3 c% x* t7 E; k: u */6 L* y% _3 B. c4 x9 T- B
public List<DeptVo> getDeptByList() {0 B& B1 K1 @& Z; h- M
// 按条件查询部门信息
1 I6 K# l4 [& ` List<Dept> deptList = deptMapper.selectList(Wrappers.emptyWrapper());
; W, m2 B @6 I" E( H* Y List<DeptVo> deptVos = deptList.stream().map(DeptVo::new).collect(toList());3 I) Q6 v. C* m$ r$ a. H5 X
if (deptVos.size() > 0) {
6 P/ V5 h) W8 Y f0 f, R addUserInfo(deptVos);
: _8 F4 S/ A+ V; ? }5 I5 F7 p5 S/ x
return deptVos;
, C2 p" z; \, m0 B}" j% S/ `; {: Z% q( m( ?6 g* Z
</code></pre>
3 U% n! W" z% |& }+ v$ t) T; q<p>补充附加信息</p># ^ [ L- R0 t( J- d5 I1 x& N
<pre><code class="language-java">private void addUserInfo(List<DeptVo> deptVos) {
# }, z, g& [: E( L1 }$ @0 V // 准备deptId方便批量查询用户信息4 [2 ?% y7 Z) I2 s# Z
Set<Integer> deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
6 x9 [- ?5 s" q! b7 ]# X5 f // 用批量deptId查询用户信息. d( V$ L) l/ n! }' L- v7 b
List<User> users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
. K8 _% A- @7 { // 重点:将用户按照deptId分组
6 B0 }6 a+ u' m. p Map<Integer, List<User>> hashMap = users.stream().collect(groupingBy(User::getDeptId));; R6 l! Z" F& }2 R, f- F
// 合并结果,构造Vo,添加集合列表
. I% h8 O6 c( x7 V9 C% ] deptVos.forEach(e -> e.setUsers(hashMap.get(e.getDeptId())));* q1 ]% V* w2 ]' _
}
& |3 t2 m0 f2 S( o/ ~. c5 d</code></pre>
' V' m/ x* D% k" o2 W<h5 id="2理论分析-4">2、理论分析</h5>
' Q: g5 T, C4 x& p<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>7 K4 f4 ~3 F C: K% r
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
& r4 V! S- H" ^6 V R! v, P<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>" D& j- ]. p3 o* ?7 k6 ^
<h5 id="1示例代码-5">1、示例代码</h5>. w( F+ K- r7 w8 \* D
<pre><code class="language-java">/**
. Q' S" `1 \3 n- ]) O8 \# m q * 分页查询部门信息(其中一个部门有多个用户)
$ g4 |) e( Y6 c* L; Q */+ J" r( G3 j$ I: N, _% }' y
public IPage<DeptVo> getDeptByPage(Page<Dept> page) {/ h+ n# b2 U* s- z1 R+ @3 P5 w3 G0 p7 A
// 按条件查询部门信息
( \3 l2 J$ S# g IPage<Dept> xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());4 y' j9 c2 t* j# R9 P
IPage<DeptVo> deptVoPage = xDeptPage.convert(DeptVo::new);/ m# Q: F0 p* |( M. c
if (deptVoPage.getRecords().size() > 0) {% K8 l3 f9 \5 e# ^3 d
addUserInfo(deptVoPage);* E0 X$ H! }, c6 J: H5 \$ Q& m* J
}
/ M% t; V6 G0 u0 ^ return deptVoPage;: S f1 C. w! o* u, w% }
}
9 c+ J* E; R2 @6 ~; u& ?</code></pre>
2 b! {4 _ B7 O7 a& t4 v<p>查询补充信息</p>
* j( N* U; E) r. M7 `; t5 U6 t<pre><code class="language-java">private void addUserInfo(IPage<DeptVo> deptVoPage) {
5 ^$ G- M+ |7 L! m0 k% t // 准备deptId方便批量查询用户信息6 V, O( F# D% ~
Set<Integer> deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());" R: a$ {( U4 a* P2 X$ F. Z; `% ?7 l
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);0 N' n; f. v% |$ _. A8 V
// 用批量deptId查询用户信息3 L8 h5 S+ o6 s* B
List<User> users = userMapper.selectList(wrapper);
+ r: k: j% _+ I6 i# N( X s! L // 重点:将用户按照deptId分组
6 r8 L) D5 O5 Y9 ~ Map<Integer, List<User>> hashMap = users.stream().collect(groupingBy(User::getDeptId));
. m0 R: B; s, {! J) v; R$ i // 合并结果,构造Vo,添加集合列表
) r. O1 S; {3 q8 C! O$ ` deptVoPage.convert(e -> e.setUsers(hashMap.get(e.getDeptId())));
( {1 k# X: ?; m}
& c9 u; ^8 x |! g</code></pre>% ~) ~. }2 ^0 {+ y/ ]0 y/ h- V
<h5 id="2理论分析-5">2、理论分析</h5>, @# ^2 K y( z9 M
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
4 o: x/ `, V, u6 n! J3 j9 {, K<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>, [& d0 @* v6 d0 o. d, i5 K
<h3 id="四多对多查询">四、多对多查询</h3>
6 A& p$ P3 P) g<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
# _" Q! g ]! W& l: p/ T- y* q2 U<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
; t3 M: E! g1 Z* v$ ]; Y$ y/ p<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>3 R- Q' C$ g- N
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >- H: l" ~( K! Z
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>9 o$ T+ u' S, S, _& ~6 ~
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
- a J% H& l7 O, S7 h) E<h5 id="1示例代码-6">1、示例代码</h5>
0 K1 t7 ^& I! c# b<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {8 K5 Q. g9 M8 ?/ P; W
// 通过主键查询学生信息
- I! L- I; F/ b% m+ R _" i6 e ? StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
1 N* c9 ^# }4 X/ n4 \7 X8 E LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
: k. [: b+ Q+ @ // 查询匹配关系
8 a5 m! ]; i2 F6 c List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);
2 T; f4 `( F' H Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());& H# A' S% b* {/ M7 @; T) A
if (studentVo != null && subIds.size() > 0) {
+ d- J- ~6 e/ w) `, X/ f- r' h List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
& H% @7 g+ [) d; \ List<SubjectBo> subBoList = ConvertUtils.convertList(subList, SubjectBo::new);& m' x& W, |* C( b6 l& A4 m( w: g* y
HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);& x% \% c; x# P" b( v$ I. P
subBoList.forEach(e -> e.setScore(table.get(stuId, e.getId())));
% ~. U# N& w/ l; P; m- H4 ]0 s2 M studentVo.setSubList(subBoList);
5 I% ^$ ]$ f/ b& R }% P, h2 Y4 L1 K
return studentVo;
5 F% Z V2 v7 V}' c6 v: o+ H( _9 c
</code></pre>' u: B. @' _& [3 M. ~
<h5 id="2理论分析-6">2、理论分析</h5>
" ]8 t$ X; i1 Q" F1 _0 b: r<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
. N) G. j( F. [3 j2 e* |+ A$ Q<h4 id="二查询多条记录-2">(二)查询多条记录</h4>4 y2 s! H0 h8 _: @7 R+ A
<h5 id="1示例代码-7">1、示例代码</h5>9 S) ?- U: {3 k' \
<pre><code class="language-java">public List<StudentVo> getStudentList() {
& u* b6 a: e J& b/ T& } // 通过主键查询学生信息9 r( C% s+ u$ x: y7 v+ }
List<StudentVo> studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
3 T0 Y) B- j; k+ e. S/ c // 批量查询学生ID% Z* l4 ]. ~" Y+ I) r: |
Set<Integer> stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
- Y, p; ^3 H' y- @9 T. [ LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);5 [' F e: m g3 a% r4 t9 v
List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);
9 @- l$ S0 q8 G% D7 D: t2 r# I, | // 批量查询课程ID
1 H$ X5 u$ Z7 H" v Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());8 F. Z" P% O4 D8 j8 e1 q* R, v
if (stuIds.size() > 0 && subIds.size() > 0) {# ]: @: d \# f- T; H) _* e: w4 D' q
HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);
r# m$ i( P+ Z) m0 g List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));8 O. ` o9 m7 x
List<SubjectBo> subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
- G. I$ h" Q# c2 R Map<Integer, List<Integer>> map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
+ ^3 U7 V6 |, x& o2 ?5 b7 {7 c: { for (StudentVo studentVo : studentVoList) {/ B. V {' v! ?4 ]. I. u w" H
// 获取课程列表
# Q7 D- m U8 r$ n List<SubjectBo> list = ListUtils.select(subjectBoList, e -> emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
6 D, }7 [% ?* p // 填充分数/ N! @" A) q. H2 @9 o! K
list.forEach(e -> e.setScore(table.get(studentVo.getId(), e.getId())));
, o' M+ M S$ G" `+ `' G4 F studentVo.setSubList(list);
! W0 n+ O) f+ o" R }8 [, o9 {( R- A5 w& N
}. v) p" ^( R2 X* ?/ u' Z" n$ I
return studentVoList;7 _/ @! t) m2 l( f* z- g
}( ?6 y& ?1 Y2 u5 T
</code></pre>/ ~) C* W1 H& t- K+ D+ B0 m' O# x
<h5 id="2理论分析-7">2、理论分析</h5>8 @' p3 y# N y3 ~! k2 e% U s
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>. m3 o1 ~* Z, c, p" h. {& B
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
7 o- V5 R5 y& W ~' a1 s; g7 B( z<h5 id="1示例代码-8">1、示例代码</h5>1 Y4 M) G! Y. A( n+ |7 c
<pre><code class="language-java">public IPage<StudentVo> getStudentPage(IPage<Student> page) {
, p5 i) @9 z7 x( Q! L // 通过主键查询学生信息
+ X* G) S: {9 U3 L3 L' _# d6 h/ j8 Q. h IPage<StudentVo> studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
2 j) b. h0 @# p- }0 y& n: p // 批量查询学生ID
& o( M$ P" |0 F: @7 T Set<Integer> stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
. p% E1 s4 r+ \8 _1 s3 m, D LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
) w* B* Y( A8 A h e // 通过学生ID查询课程分数
/ b1 A$ T4 e: n! ~( F' Z2 y/ t$ k List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);
8 S& l1 Q z, U1 t) ^# i // 批量查询课程ID5 l- g% f- y+ U; R6 v
Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());& A6 X" B ?4 q5 A4 ]2 a- v
if (stuIds.size() > 0 && subIds.size() > 0) {
1 t+ `1 ^* U/ F8 o1 \: L2 | HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);0 N& w7 _. Y- o8 Y2 C
// 学生ID查询课程ID组- C, m5 q {9 D- N
Map<Integer, List<Integer>> map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));8 K4 Q: u( s0 M5 ~
+ @! [$ {/ d- v% b( T8 j List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
& {0 K2 M# I9 ^ List<SubjectBo> subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
0 O& b! M/ ^7 ^" \ for (StudentVo studentVo : studentVoPage.getRecords()) {% O$ K5 i) {3 c V! j& G
List<SubjectBo> list = ListUtils.select(subBoList, e -> emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));7 y. r! s+ O# b# ^" T" G8 t+ \
list.forEach(e -> e.setScore(table.get(studentVo.getId(), e.getId())));, i# u5 w( p5 L$ B8 I
studentVo.setSubList(list);
Z% H+ x2 C P( S$ ?2 M; x }# W) j/ n9 N/ Q# W9 q0 `6 M( G+ M8 C) w
}( w' C! w0 g; y% u
return studentVoPage;, U) Y% b3 m& a# [' m: @+ P
}
' L; G( S" s2 ^; e: z& {" E</code></pre>
2 l& s0 L/ E4 ]% q6 O! O- M' I<h5 id="2理论分析-8">2、理论分析</h5>) h( A$ U- m7 @5 L6 E9 {: A1 M
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>8 \/ p- ~; `6 H! z d9 A3 h
<h3 id="五总结与拓展">五、总结与拓展</h3>/ r7 }* l: ^8 d; C M' e0 n$ m7 e* U
<h4 id="一总结">(一)总结</h4>+ ~) F1 n9 o. K; a
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
7 u0 Q8 t- T' A/ F' a* g$ l<ul>. O9 v8 \2 g' y) Q
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
! ] `( O5 Y8 | |- I<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
+ D- F& t/ B! J2 P<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>& u7 X! @3 b2 r9 Z- |4 C$ {
</ul>
! W+ _6 {( e% R* M<h4 id="二拓展">(二)拓展</h4>
: W* \: Y$ _: w" F1 G" L; I<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
( E# F+ s* ]3 {- L$ {8 a$ X+ W1 }<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
% I1 N' |& @3 a5 F1 b; m<ul>
! Y$ K& }+ [8 ~7 i* I* \, r& z<li>当数据量较大时,仍然具有稳定的查询效率</li>. A1 W! Q9 B* u+ N2 R0 e
</ul>- k- f5 e- I1 M
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p> ]. W3 F& n! G( ]; ?+ E
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
! W& R: [* X* e% `4 n/ J4 b<ul>
' ^8 [) F! C. M3 N" s' Q; U4 v<li>与二级缓存配合使用进一步提高查询效率</li>
, H" u( G1 w9 M. H) D2 s! ^</ul>" s) j2 e8 R8 t0 {3 M
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p> p/ u" ?: h$ a0 ?7 p; ?
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
5 R) ^; I: C- [6 S9 G% f3 [# v1 {& Y9 O3 U1 E' B* e% _* S
|
|