飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7953

主题

8041

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26189
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
' \7 p; p) v( k! e2 ]; b
<h3 id="一序言">一、序言</h3>
. F! n7 R1 W5 n<h4 id="一背景内容">(一)背景内容</h4>
7 y# p% R" @/ r# g+ F<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
$ v, j6 i) i. `<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
' R2 p) E; w2 d4 }  D& O4 }" A<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
7 c) Z1 A( _9 @: X# f+ z& a& N- M' L<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>! I6 P4 Q  @1 u1 ]* y
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >, R3 ?* r1 G$ x* [
<h4 id="二场景说明">(二)场景说明</h4>+ E( q( b0 W, p+ y
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
8 B1 W; u! f( |& t0 \<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
1 P$ o4 Y: k$ @9 G9 X<h4 id="三前期准备">(三)前期准备</h4>
& Q( z. S) f2 X. ~# E<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>( d, N" L6 |: B
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >* u+ L1 o* C9 h4 m
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
$ P7 k4 d3 k1 ?- Q<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
5 ^; F# c% F  K# s; Y<h3 id="二一对一查询">二、一对一查询</h3>( q3 x2 c  q# ^. {) ~
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>1 G6 [3 _2 J2 m$ ~+ }# D3 F
<h4 id="一查询单条记录">(一)查询单条记录</h4>
# q& O# f6 n3 y/ U* d+ b<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
8 @$ @# X- S2 D6 o2 r<h5 id="1示例代码">1、示例代码</h5>
2 F* q- r( S) ~<pre><code class="language-java">/**
( [) v+ l8 [7 r/ a8 f) A  }- ]. Z * 查询单个学生信息(一个学生对应一个部门)
7 u! V% Q: z( p6 T */
+ C8 r! k0 {9 Upublic UserVo getOneUser(Integer userId) {0 b7 ?! |2 a1 W' Y" T
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
" j  N! M" i. l2 ]( [! L        .eq(User::getUserId, userId);; o" t2 c3 ?- {
    // 先查询用户信息5 D) @  ]- F" {* Q6 S
    User user = userMapper.selectOne(wrapper);
- D6 i1 e# }7 y% N$ s0 A    // 转化为Vo
/ n6 o4 `) \9 C# ^- y; x3 F, ~    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
3 s. s8 |" f% M) r0 ]- L    // 从其它表查询信息再封装到Vo+ L, r7 Y7 z  a! Z! X
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);' \9 d( O; p. ?$ |* Q
    return userVo;) x0 j2 }1 x2 j2 N  @' @# w
}( a, ?; k- V# y; ?+ [  B
</code></pre>$ q  h! c8 I8 ~/ S
<p>附属表信息补充</p>( C4 |; @6 G8 }( s# z
<pre><code class="language-java">/**
6 w! R6 \, \- A; y+ u * 补充部门名称信息) E- A( {$ j# i9 V. _# X' J0 ?
*/5 |: r) Y' d2 j  s$ C
private void addDetpNameInfo(UserVo userVo) {
  T2 K' r9 r* p  [  q    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)) p3 G, z) I- |9 r
        .eq(Dept::getDeptId, userVo.getDeptId());
6 \4 ^5 G$ L6 U% f5 G$ a    Dept dept = deptMapper.selectOne(wrapper);  [/ z' i1 G# m( C# W" Y5 l
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
0 |: g$ t2 ]% O, l3 }}
- I% J- [7 |. ~</code></pre>
7 U3 d% g2 U- B4 b: n<h5 id="2理论分析">2、理论分析</h5>) ~' E! C, u5 [: r, K' B' f
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
9 Y- b- j/ {# c& V2 F. I' Q<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>" j4 {$ n5 b' X+ R+ v7 j8 E6 }" j
<h4 id="二查询多条记录">(二)查询多条记录</h4>
8 Q2 s( }9 D. t6 V4 H<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>- r7 Y+ k* w% I, @
<h5 id="1示例代码-1">1、示例代码</h5>( I0 K) x! [( R+ s- o# s
<pre><code class="language-java">/**
5 E" p3 n" B7 @: I, m0 c * 批量查询学生信息(一个学生对应一个部门)
1 D' m& y- ^& o+ r% B */# m- f1 j+ u5 Z; E2 E
public List&lt;UserVo&gt; getUserByList() {
, [) e3 _. U: Y" I6 j: o    // 先查询用户信息(表现形式为列表); K" c3 i6 c  s' l- C3 M' c9 p, ~! U
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());& w( H0 [; ?) Q
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());  I! P: ~2 g; I  B
    // 此步骤可以有多个
9 C+ j2 A* A: N4 h. G0 ?    addDeptNameInfo(userVos);
+ T  {4 B  ^8 r( m! @    return userVos;
; w: t" h6 F1 Q' S% P8 A7 P% h}& L! E7 k+ o  L" _+ W1 j2 e
</code></pre>: J0 j3 A9 \* i7 X. x4 a6 y
<p>附属信息补充</p>$ R, p; j2 {$ ~+ c+ N6 Y
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {
0 Q$ i. `* W/ Z4 B( {# t    // 提取用户userId,方便批量查询, a6 g* ^) ~# o
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
3 E7 U2 G1 q. J6 V5 ?! C5 _    // 根据deptId查询deptName(查询前,先做非空判断). g% Y4 e; d1 f9 e  D! i6 l
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
, |& t' O4 h6 k6 d  J: v5 Z    // 构造映射关系,方便匹配deptId与deptName
( D7 R. v4 U- p6 ]* H( N    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
8 L/ J$ }7 J9 u4 T    // 封装Vo,并添加到集合中(关键内容)9 r! u) |9 x$ R! z, X
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));( l' L3 T# A+ T: {7 ?5 V) h$ t/ y7 c
}
' v: N0 h% u7 ?1 y/ u8 Z" A9 Z</code></pre>5 P: L0 g# _7 n9 S7 j: ]
<h5 id="2理论分析-1">2、理论分析</h5>/ g/ w6 N, J0 N8 p% V. z
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>( p3 J* h# K3 z
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
+ V4 {6 y( n0 b2 k; ^4 j( {: @<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
3 m# y0 Y0 A% g$ x: X. K( c<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>8 X7 Z4 Q4 z$ l( H% Q
<h5 id="1示例代码-2">1、示例代码</h5>$ B: N5 o  |0 b
<pre><code class="language-java">/**0 r  |4 I1 Z) ?& l; M( e
* 分页查询学生信息(一个学生对应一个部门)
( X( }/ D& v+ N */
, E4 R7 |5 ?4 ]/ H! {public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
+ L9 y7 U: T  n: P8 H5 ]    // 先查询用户信息) x) D" ?/ Z# A9 ]- \
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());' T( N" Q' X" p8 F) Q6 K
    // 初始化Vo) C4 c: `+ H/ [6 g& O  X% N' H
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
* G" d! i: L% F, J8 B    if (userVoPage.getRecords().size() &gt; 0) {
, Z; U- }( p  I  f0 Z2 N        addDeptNameInfo(userVoPage);. R! V4 Q# z. X5 I+ g9 ?
    }
  I# _7 M+ a4 U0 N5 r# V( v    return userVoPage;
5 K4 I% s* ?* x  A/ E1 H" K}
) V: Y% z6 R% Z/ x</code></pre>
# H4 o+ j1 R; x- S. W<p>查询补充信息</p>
# ?% `9 o) A+ U4 C1 |  r$ h$ E<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {  q/ ^* \5 I" s; l
    // 提取用户userId,方便批量查询
- @: ~; ]( B/ C$ E7 Z3 t    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());* q" N. E6 z3 v# d7 S4 N# h
    // 根据deptId查询deptName
& U( \6 }6 E9 W    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));) o" y, O7 k# x6 R
    // 构造映射关系,方便匹配deptId与deptName
* d5 R& Y9 r' J    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
7 F2 C  o% F$ l2 w4 b/ N* _    // 将查询补充的信息添加到Vo中( A5 @. L4 j  Q: D  T, G# A* W2 r
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));4 b# Q2 h) @: N1 U7 F
}$ m7 @% o1 X) _5 b: w' p
</code></pre>4 f4 k' p) }* Z) {* i: l
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
9 t2 u: x2 z! U<h5 id="2理论分析-2">2、理论分析</h5>
0 X* p4 E* E% v! e<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
. t2 D! S3 `& A" `0 U7 o/ g<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
1 A; _0 {1 q0 Y0 r1 D<h3 id="三一对多查询">三、一对多查询</h3>
7 f, Z' g0 E) P<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
* _+ y# b) ^2 y<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
# F2 k5 N  W0 u7 a3 T6 j- k" x7 n7 x<h5 id="1示例代码-3">1、示例代码</h5>
/ b) X( {$ \4 |1 D1 B<pre><code class="language-java">/**: R% Q/ n) b; d$ t7 r, Y
* 查询单个部门(其中一个部门有多个用户)
% [2 u9 i% e4 I- |$ L/ j( c0 \' { */
* w, O3 n; g  e3 ~$ t9 i) I3 Qpublic DeptVo getOneDept(Integer deptId) {) N' i: f0 Y$ ~4 ~5 c5 T' A; S
    // 查询部门基础信息' G# r0 u! {' V0 r& u" o$ U0 b
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
, H! o+ C1 t  w0 d' D    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
5 b/ m& b/ Y& l; V( k    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
9 ]6 C, q' d% I4 H/ D. ^4 Y    return deptVo;
, T! a# a6 Z" i; W/ r% @}* g: S9 \; D' \- ]. y
</code></pre>7 \4 n  R; b: y( ?: N7 v  u! {! q# P
<p>补充附加信息</p>
) n  D6 w: ?, u3 Z  O# B<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {* U8 j! I3 m; z) l+ n' L: p" P
    // 根据部门deptId查询学生列表
" t0 D" T6 _6 t. f! b& y& E' V    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());8 q# j- c0 O) l5 |9 H  x
    List&lt;User&gt; users = userMapper.selectList(wrapper);+ ^) T$ q! M+ S  {+ F5 A7 k
    deptVo.setUsers(users);
# v( }2 Z. ^: u& j- x( [}) s2 Q9 ?5 x1 H0 Z! N/ C) R& Y1 }8 L: @
</code></pre>: ~: s  T2 V) D  N4 i# M
<h5 id="2理论分析-3">2、理论分析</h5>- ^* m0 b" l, A, U9 b/ |
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
6 @' q2 \8 A+ m" X$ H3 i$ ?( \6 |<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>: b$ a7 C- Z4 s- @- a. v% Z8 M
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
& l) M, ?$ Z* j3 R. _4 X  g<h5 id="1示例代码-4">1、示例代码</h5>
: S* h6 U- d, n1 q* O$ H<pre><code class="language-java">/**
* T; X, R# h* o4 B. f3 E * 查询多个部门(其中一个部门有多个用户). Z5 }+ v' w0 ^6 k
*/
! o" J7 C9 ^3 e* Q: B. ~8 M* zpublic List&lt;DeptVo&gt; getDeptByList() {( @3 r' N, _- X1 \& d" H: v
    // 按条件查询部门信息, G3 \" T9 E2 Q  I% M& d% A( o- E. p
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());& V* I1 z. k+ {" b4 `8 B1 _
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());! X, }. W' v/ n9 ]# k' t: r# y
    if (deptVos.size() &gt; 0) {9 k: c0 h. t5 Z  ^8 _
        addUserInfo(deptVos);5 J" t5 Z8 o$ k: H6 z
    }& L- ~  l/ T" p  q& C3 a5 C: V
    return deptVos;
" s- B3 j! C6 H}2 A- g' N5 Y# h+ Q! n% T# Z: X: T
</code></pre>
" G% ]8 |3 Z8 H/ K<p>补充附加信息</p>
" F" r7 W- E9 u3 n  l* T<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
6 @- Z: J! {4 F; F; H  S    // 准备deptId方便批量查询用户信息# |( |6 D# q5 m
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
1 E6 e0 [5 [# d$ @4 Q' @9 V    // 用批量deptId查询用户信息
9 ]  z" O7 F* s1 z    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
9 y/ k# j8 j; J    // 重点:将用户按照deptId分组
3 l$ n5 B; D5 Z9 i- _% F( B    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));2 y4 r' D" P; d) e# G7 {' M) ^
    // 合并结果,构造Vo,添加集合列表
1 q- ?' E7 O2 h+ G' Z) Y1 `    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
: q; T: V, l! L! Q$ U% i  w+ ^# A}
! o% a/ |9 s) f8 c% I. ~% C6 @</code></pre>% u( V$ S5 d# K) [; b
<h5 id="2理论分析-4">2、理论分析</h5>, ^+ x: d. l  E2 O* }0 m1 b0 a
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>) p" e, y1 h+ G0 P9 l0 J: B
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
; F' D& G" W, w  D<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>% A" G) B$ S' b/ E6 Z
<h5 id="1示例代码-5">1、示例代码</h5>3 j6 J7 R( l5 {
<pre><code class="language-java">/**7 ~3 i9 t2 m* ?* W" {8 b9 E
* 分页查询部门信息(其中一个部门有多个用户)
9 P& k1 z' C1 y1 q' d3 V */
" v4 V7 V5 k0 |' L* x7 e- Dpublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {8 i6 Q9 K7 E: k. @9 L
    // 按条件查询部门信息8 I1 O( o/ `% l# I
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
  K) a9 p( X4 D, p    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);' a0 e8 O" ?6 B1 x$ t: \( M8 ]) j
    if (deptVoPage.getRecords().size() &gt; 0) {* g* s8 J& W  c1 F2 E
        addUserInfo(deptVoPage);
8 h" E* _$ @2 d( U, k    }$ B7 v9 R( D: y% u4 L6 x
    return deptVoPage;
/ \1 s' p  u* }: Z) A$ L7 S}, L" H. D7 p* p# |" p( W/ |
</code></pre>
9 @9 y% n) L- O% l0 u' G" Y! L<p>查询补充信息</p>' c' w. B  M; J6 i, {1 [5 H! y3 h
<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
9 \% R$ S( a6 {3 c    // 准备deptId方便批量查询用户信息
/ d  k% @2 ~* {6 U) o    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());4 s& |2 k" T# b! i. o* J
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
1 j& H; ^7 ]/ B# N. b, {6 z( M    // 用批量deptId查询用户信息
- i7 d+ C, Q" |    List&lt;User&gt; users = userMapper.selectList(wrapper);; u$ b2 z* f# V; c% K# O
    // 重点:将用户按照deptId分组7 [* F/ ^" l4 C8 D
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));* }& J7 C8 S: ^5 U
    // 合并结果,构造Vo,添加集合列表. J: H* U; N& b
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
) Q) k1 d$ [  L* H/ A- p. b. d6 w}
: S8 I; J3 |9 z' m( J# [" p</code></pre>" t% f8 f7 G/ Q) n5 X2 r! {
<h5 id="2理论分析-5">2、理论分析</h5>" N. M4 Q" T7 o5 W3 k. ~# t7 l
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>& K- \# \; ^1 ~
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>% p6 k4 b1 i0 G# G# u5 Q5 ]
<h3 id="四多对多查询">四、多对多查询</h3>& Q' e* K/ d( X+ E+ p1 \
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>7 z# j4 b. _; f4 m
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>* Q# @; v  E$ @" L. I3 G- M
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>3 k. D* b* S0 q; O7 I$ i9 l( _
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
, ~5 ?9 ?  R- D, ]. l<h4 id="一查询单条记录-2">(一)查询单条记录</h4>1 K0 j8 k' k8 i" u
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>5 u) i6 C6 B6 P
<h5 id="1示例代码-6">1、示例代码</h5>
8 U2 o* f9 p; ]* b* ^: O<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
# c! R- ]9 v3 V. E6 r    // 通过主键查询学生信息
' r( ^! E; F  e. S8 P, K) [    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);. `9 t7 `" d. E' O/ A
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
8 l* e6 O1 ]2 i    // 查询匹配关系
) }( e/ t" G4 P0 T- \8 ~    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);; J6 U" C  h: v- O" O8 j& I+ |
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());! x5 D& e" l/ u& d
    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
+ t- s  B; T% `* l' c1 F6 ^# C0 g        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));0 Q1 r( F. W/ z) T: k; s: r
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
- O4 N( v& F# K        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);$ I2 I# |% k" g6 f
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
9 F( m( A& p' V4 m        studentVo.setSubList(subBoList);
% {5 m* J6 A: N8 B$ Q& S    }( p7 r4 }3 |. U. C
    return studentVo;
7 d3 o. ]7 h2 T7 M}5 f  D" p7 r( I6 Y2 n+ [" g
</code></pre>" t8 F* i& W4 |
<h5 id="2理论分析-6">2、理论分析</h5>
2 F, h. @% h* @; ?. d, e/ q<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>. }3 L" u  w/ Y9 A- j& `; i
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>: G# R8 p9 [' ]$ H( O* I
<h5 id="1示例代码-7">1、示例代码</h5>
9 f6 ^+ R# {9 ~- H<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
# Y  D8 I7 i; y; q1 A3 t& J; [    // 通过主键查询学生信息5 Q' G* x/ _7 P
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);( y3 Q$ ~* V! w! e9 O5 E! s8 e
    // 批量查询学生ID, i2 [3 b$ z% L) L
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
4 W( ?; z& o/ J8 O  N    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
! D8 Z- |' ~5 S) l5 h& Q9 R    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);) j) l# Q( C) b% W
    // 批量查询课程ID
# ?6 @. t% H2 w; l. Z    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());* y( K! Z- M' ?8 T5 Q
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {6 W" i# E6 \( ]/ _5 }. q7 v
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);; m$ h3 C# e5 M8 i
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
% M- _* K, Z+ ]# M        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
" x8 n& i6 H4 L6 _$ X, g, R0 ]. l. m' l        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));/ }6 g! l4 G. t1 A9 c3 o
        for (StudentVo studentVo : studentVoList) {
5 q! v5 l8 G- O4 \: E% I            // 获取课程列表
) ?* O  Q9 C# ~; S( ^            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
3 j8 t1 C; k1 w- t& L- d            // 填充分数) i- @5 D" W/ ?* k7 v
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));5 i5 t: D5 u! p5 C; \  y
            studentVo.setSubList(list);: e( T! C' P5 M! c' W8 C0 D- {
        }$ {3 \, V- n6 d' I2 N
    }( @" p7 P6 f% s- i
    return studentVoList;( h7 X% ?! O8 d
}
7 ^9 u/ r, G  i$ d8 l: s7 K: x</code></pre>- z* l: N% a# o9 T4 }% T
<h5 id="2理论分析-7">2、理论分析</h5>% e3 o2 U% t' B$ c+ x6 K0 t0 g( b- b
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>7 z9 ^- K0 @. q- \: O8 T7 ?
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
; S  w/ u6 O( o% {( f2 b<h5 id="1示例代码-8">1、示例代码</h5>/ F. Z3 D' f9 d' j& l! V
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
9 i0 v4 X# O; j3 n2 {' ?    // 通过主键查询学生信息% q( ]& O2 c: s8 m& j# ]2 {
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);% P- h* Z# _; K& j# G" o
    // 批量查询学生ID
- W+ w3 U1 D7 e1 f8 b  d    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());1 i' x8 }: h, N6 ]) ]: J# l) M
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);! k6 h- }' g; o" Y9 C( d5 k
    // 通过学生ID查询课程分数
' @& M) O, q& J  g    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);$ q+ D$ q7 d- M* \; F% Y
    // 批量查询课程ID
! C" M# c) U7 ]5 C- G    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
+ S; N! `6 W* i" }4 W$ J$ K% t    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
, R0 X1 C' p) Z0 a/ r6 J" p, {        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);- m/ k- d" P2 q) i6 E7 O
        // 学生ID查询课程ID组
6 k+ O* C4 D, {6 T9 _5 d: ~- t        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));" S- Q! d, X, B7 L+ e: N& I; }
# t+ p/ S$ r& z5 b5 @* A
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));( f" u" p# i/ R( [
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
$ W6 v/ j# q- ?# z9 \1 ?* ]5 W( q        for (StudentVo studentVo : studentVoPage.getRecords()) {9 t5 b+ p' \# h3 K* S4 }/ }& L; |
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));, H( ]( |; a7 h* K) |
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
7 m2 X% \; |7 p6 h            studentVo.setSubList(list);
4 o! @! s; l. d        }- S1 l! a/ ?7 X5 T1 I; c0 v* r. s
    }8 H2 I5 d% i% U* U$ w
    return studentVoPage;" R) j* c3 o- ^2 x
}
# b' @8 Y- L7 S# p2 y3 J) M8 ]# L</code></pre>/ Q& N; n) f0 f1 M
<h5 id="2理论分析-8">2、理论分析</h5>6 m: b& T3 _  [+ s. f8 k( r
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>0 v- ?  s2 q5 z$ Z# u
<h3 id="五总结与拓展">五、总结与拓展</h3>
: s6 N- @2 v& W$ T$ k8 f<h4 id="一总结">(一)总结</h4>4 ]) O/ K" T. m
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
  i7 C, B& |( q<ul>2 T6 o+ M- B. M7 n! ]. k# N( B
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
  Y1 X% I1 M# ^<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>0 s, t: L% }; T* x% }! l
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
- Z* E! _8 D. w$ `% K: G- q& s</ul>  N: a4 Z1 y3 h1 a2 f& R% ?8 J
<h4 id="二拓展">(二)拓展</h4>! b' J+ l- q% u
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
% l" ?* i& x2 h7 M7 o<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
/ ]0 D. _1 j2 E<ul>, _$ L4 {$ Y+ `, I8 g+ ]6 R
<li>当数据量较大时,仍然具有稳定的查询效率</li>
6 k2 m. P0 Q8 Z% i</ul>. z# [- e2 m2 S3 y9 P( r" L2 A0 D9 o
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
7 J3 {3 E; [# {; _4 o<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
- h3 Z; g, u/ f8 ?" x' K<ul>3 }4 {2 R8 _0 |% V4 o5 Z3 k- F  h
<li>与二级缓存配合使用进一步提高查询效率</li>2 g% t1 t! Y7 V5 Q
</ul>
8 s, f6 j3 c5 J& g<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>$ g8 P* X$ |# _0 I& z  V; V
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
: f7 w+ C0 B, l) Q
! F$ l6 u' e$ ?( g/ Y( w) Z
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-11-25 00:32 , Processed in 0.066325 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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