飞雪团队

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 17530|回复: 0

MybatisPlus多表连接查询

[复制链接]

8834

主题

8922

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|飞雪团队

GMT+8, 2026-6-3 08:50 , Processed in 0.070570 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表