飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8042

主题

8130

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26456
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
9 ^' k4 [5 w$ ^: U. N: C( i
<h3 id="一序言">一、序言</h3>
5 F7 k: B4 i. ^3 Y9 Q0 o  N3 q0 r* I  n<h4 id="一背景内容">(一)背景内容</h4>
( \  n9 C0 B# }0 S+ O% z8 v<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>1 _( k0 I7 o. X
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
9 g$ b$ l) r- h% L- V, F+ \  z<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
' q! i5 J! s. d9 B<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>. L, x; A( f/ D% W
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >( P8 z# L. m/ E3 k# E
<h4 id="二场景说明">(二)场景说明</h4>
, R: i7 Z+ W& F, g7 \% P7 L7 q<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
, H6 b. v, r: Y) m<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >% Q9 S" @9 i% `0 h* a* ]  g
<h4 id="三前期准备">(三)前期准备</h4>
% Z% n3 K- z7 Z5 d9 ^. E$ S3 ?<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>% a- \: T6 Q8 G8 |# ~/ j5 J
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
4 y6 s) p  L% Z$ E<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>3 p+ J9 U" k4 y# n1 d$ g
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
" s4 N1 R* n3 n8 ~6 }<h3 id="二一对一查询">二、一对一查询</h3>( z; O! N$ Y+ F% h# ~5 Z" G* D
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
5 n9 V/ a* J5 x8 N+ t/ j; l8 ~<h4 id="一查询单条记录">(一)查询单条记录</h4>. L1 `; |. ^, a' m; c3 z
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>. T; K3 c3 [8 ]. i' h2 U: Q; V' }
<h5 id="1示例代码">1、示例代码</h5>9 L7 E( t( A6 b& t# ^: h7 H
<pre><code class="language-java">/**
- m8 d8 w3 f8 V! h& j * 查询单个学生信息(一个学生对应一个部门)) m! u. X  g/ N' E+ n8 @8 `
*/
, P" @; B; _: W8 M- a0 Q: spublic UserVo getOneUser(Integer userId) {
& b- ~+ B+ R* h" @    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)0 f# ]* N* M3 w6 l( M# X9 \
        .eq(User::getUserId, userId);5 D+ G, O; h- p/ K! U
    // 先查询用户信息
/ \1 T* ~; w$ x/ N    User user = userMapper.selectOne(wrapper);
- N* U; O* m' j/ V    // 转化为Vo
( [2 ~' }0 P% Y    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);  ^9 K! B4 y0 ~) s: v) n+ s
    // 从其它表查询信息再封装到Vo- z5 }6 k" A& ]5 N' m
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);, k. u% }- W9 b
    return userVo;+ B! c8 X4 Y8 ]3 ]
}
1 S7 p% I& S( G$ P' C5 F- ~4 X1 a</code></pre>
0 @1 ?. P3 Q2 F8 I: u: g1 o<p>附属表信息补充</p>
& n( d& ?" r( H<pre><code class="language-java">/**0 \8 W$ }& M$ E8 x% d4 m- f6 @
* 补充部门名称信息
' w6 k! `& C9 ]' a */3 a+ u" k, n9 u7 i% t) E. }2 f
private void addDetpNameInfo(UserVo userVo) {
. v: C( V, O1 R# Z: K# f    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
$ o( o3 R. p  D2 ~- \        .eq(Dept::getDeptId, userVo.getDeptId());! S+ \6 q- `' S" a1 [' I
    Dept dept = deptMapper.selectOne(wrapper);; L9 @2 t  u; V$ T
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
: |8 q& `# N' d" X7 }6 y6 c}$ b& m9 |; \7 W( K/ K
</code></pre>
4 V/ H" K# ~0 z4 {; L' c+ d; g<h5 id="2理论分析">2、理论分析</h5>; m! x: e+ P; [" l3 [# \
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
) s* @3 o: o$ \) p1 E<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
/ q. b8 V9 P% ?& k% h7 r<h4 id="二查询多条记录">(二)查询多条记录</h4>
$ \) g* x; B. w! A  |0 q<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
- G% h5 Q# {4 [' t<h5 id="1示例代码-1">1、示例代码</h5>
- ?! b9 _& M" A( ?: e<pre><code class="language-java">/**. b. m+ Z4 M0 X! |/ Y
* 批量查询学生信息(一个学生对应一个部门)
0 e' l! H/ B. a6 f */
% [- z, \& n1 vpublic List&lt;UserVo&gt; getUserByList() {
  h: `4 [8 H( s- i, G    // 先查询用户信息(表现形式为列表)
9 h9 h* h- I" W0 d& M$ S  b    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
# u2 L  @0 K3 Q+ O3 e    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());. b5 l9 p4 X. R
    // 此步骤可以有多个
$ g  b% a) n* t7 s    addDeptNameInfo(userVos);
, m" S) X) G  S4 c' n2 @" W    return userVos;, I$ h' w, q0 q/ S
}
4 L5 \3 V# ~4 A7 H. z5 Q</code></pre>3 B0 w; j& c5 i* K/ p. D
<p>附属信息补充</p>
7 h* o  i& |. [" g7 W( n2 Q<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {
0 \6 l) ^9 ]* g; K+ ]/ b5 `    // 提取用户userId,方便批量查询" w8 C) H" q' ~/ ^
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
! Y/ x3 k9 V) @& r' W$ ^2 c    // 根据deptId查询deptName(查询前,先做非空判断)
* U! B. b. D2 e! G    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
9 ]! Z2 @+ i$ \. y6 T: l3 n. y  a$ Y    // 构造映射关系,方便匹配deptId与deptName) R" n! c1 g: m! _8 P  J
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));) R9 K# p4 P8 z$ q
    // 封装Vo,并添加到集合中(关键内容)6 `0 X) @9 M2 y: i' E, H
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
/ K. Q2 {* w( \6 U  e2 y5 X$ s}
, S. u# F9 S# [8 B9 y* r</code></pre>
" h7 F) U6 x' d+ _) {<h5 id="2理论分析-1">2、理论分析</h5>0 q' m1 D/ w0 [. _
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
2 M! J4 v4 q2 e3 L7 u! ]6 r0 R5 \<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
# O* M" G4 G3 I! I  H+ e% O<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4># X! c1 t) ?+ @: @& q: r5 z/ T
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>6 r' Y4 n9 \+ I; M; H$ V
<h5 id="1示例代码-2">1、示例代码</h5>
4 ~( C% O$ u4 E; Z<pre><code class="language-java">/**, J: [* B/ _# f% \
* 分页查询学生信息(一个学生对应一个部门)
2 P; q  P' f( `/ ~$ E! _7 B. B7 k; n, p */& p3 |5 d: u  t! V  _1 B6 ^; x
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
& z/ U' C# S% T% i    // 先查询用户信息
& t  ~! F+ d6 E$ R% ^2 a    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());- q% N8 R* w9 ?  w' t
    // 初始化Vo
( c  h* \9 f5 n; ^" k( @# i    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);# `8 e: _& d, |# s- ~' l% C
    if (userVoPage.getRecords().size() &gt; 0) {
9 B% S+ Q6 [: ^! I* I# E3 d. S        addDeptNameInfo(userVoPage);6 ?9 m, i# C1 J  W
    }4 T2 }7 q: {6 @1 A7 I
    return userVoPage;& F: r7 J8 X! H: N+ M# ]! P* K' [
}4 e9 s1 z; W; j3 h! S- I
</code></pre>
/ z2 W& O0 N$ R( M5 O<p>查询补充信息</p>
( [/ _, g! P2 `- V' Z' B3 N* H5 o<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
( m. t/ \6 j. C+ G/ X    // 提取用户userId,方便批量查询6 M& O: n/ b! r. Z5 m, ~- `
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());  _3 `, }8 y  n+ V4 O$ P2 @! k
    // 根据deptId查询deptName
. o: ]2 G+ \) N4 u$ m8 {. s: p1 W    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));" n2 w8 Z& e& o
    // 构造映射关系,方便匹配deptId与deptName
( X8 k8 g& v) B- {% ?/ C7 ]- x& |    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
  O" a% U; y- l! c2 U    // 将查询补充的信息添加到Vo中
8 i  f: Y, r+ T+ u8 `- e# Y    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));) Z+ {0 g4 N! R+ S) w: {  ~; n
}1 \4 F# `8 [( _5 D& R8 t
</code></pre>' K0 r& I+ ]. L' Y# r  x1 `
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>' B  h. n& Y$ h" G7 f& }; Y
<h5 id="2理论分析-2">2、理论分析</h5>8 K! w) }8 o8 Y! C
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>9 l8 g8 ]6 \2 |, ^
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>( q( j) w# A1 g& D
<h3 id="三一对多查询">三、一对多查询</h3>/ h- b1 T4 a  N! @$ J
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
) L. l# G* F8 h$ L2 `" |<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
  u) y0 A  K) h  r$ F7 G3 M<h5 id="1示例代码-3">1、示例代码</h5>. a7 |' s1 ^! B* B3 b. s
<pre><code class="language-java">/**3 j$ ?! q1 z. ^
* 查询单个部门(其中一个部门有多个用户)5 E" R: d% F4 U7 x; }8 C5 s/ `% v
*/
: }2 C$ y1 a" m# ?( h7 p" R; b8 cpublic DeptVo getOneDept(Integer deptId) {* S7 n# W/ [# [$ h8 F, h
    // 查询部门基础信息
! b& Q# n2 j& \! r    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
' ^" v! Y- ~) t" v( Q0 Q    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
  K$ A6 N( B4 x9 z    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);  x7 a# W/ u& e: h) |: k% a  G
    return deptVo;
, V# l; X6 Y4 b9 R}
4 `' X$ T+ E. P5 I% V</code></pre>; c. F9 q9 U& I. W0 L
<p>补充附加信息</p>
# h) U) ~! w  x' ^4 _1 T<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
1 H+ w2 B, L0 Q8 W. ]$ ~    // 根据部门deptId查询学生列表
- ~3 s. Q+ g) N: E( M    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
$ l7 r5 D' x- ^5 J    List&lt;User&gt; users = userMapper.selectList(wrapper);7 {/ ?& B- x0 a/ Y2 C: y
    deptVo.setUsers(users);+ S" _' m8 _6 f
}/ f3 h6 i: e! \+ E2 a" X( Q
</code></pre>
" d% A* |( N; V<h5 id="2理论分析-3">2、理论分析</h5>% m- i' {" d: S. f  e+ s
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>* D# L+ B7 \  m6 q" H
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>' }! b1 o, N  \8 M
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>. X8 `' |" w, B/ c7 E- T
<h5 id="1示例代码-4">1、示例代码</h5># x& H/ A2 ~- Q, A- F$ Y
<pre><code class="language-java">/**5 n+ L9 n: u. R% ?" G
* 查询多个部门(其中一个部门有多个用户)
: j7 O/ L, O( v */
) L5 T  n( ]: m6 o6 I) `4 ipublic List&lt;DeptVo&gt; getDeptByList() {
- ]! m$ c# _' R/ i    // 按条件查询部门信息
! L& b8 S' h& T, x. P! x6 f    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());" [2 r  Q, Q# ?, d
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());+ ^" @' Q+ o; e& I6 }
    if (deptVos.size() &gt; 0) {
! b9 ~8 S" l! @        addUserInfo(deptVos);: u4 Z8 C9 D( g# ^% L( A
    }
: V/ i1 D: M+ G/ @  y. R$ e; u    return deptVos;2 G9 q0 T1 S& x& I  ^& V/ x9 g6 P! w
}8 b6 E: Z. [# f& F% [
</code></pre>
+ M. d$ q! ^$ Z1 T& }<p>补充附加信息</p>9 J% p, \# G) o8 v, J
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {8 ]) e7 p& r# @  I# ~6 r
    // 准备deptId方便批量查询用户信息5 E& }$ Q7 e3 y  S$ t5 V/ p
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());7 I& U' e% H6 f8 Y0 E6 I5 a; [
    // 用批量deptId查询用户信息) Q4 y8 N! O$ J; C
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
$ _, d+ h* e" {; E( Y    // 重点:将用户按照deptId分组% d/ o  D, o5 E- C, Y$ ~
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));7 s9 [# k2 N% b( ]
    // 合并结果,构造Vo,添加集合列表- V7 Z9 n2 k5 n2 v
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));; e  ^3 ?$ O, @4 o, h6 V
}4 q$ |% a# M5 s
</code></pre>
; ~' f" a0 j3 P! m. i% G<h5 id="2理论分析-4">2、理论分析</h5>
- h8 r$ C' u) p$ A  X# Y$ @<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>7 ?3 m  i7 ^! H9 v
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
& x0 f- ?6 y0 @; j<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>3 `* X0 v% _6 o
<h5 id="1示例代码-5">1、示例代码</h5>
* a' Q8 J# a! W+ t! W" C<pre><code class="language-java">/**5 ?* g, K. a, b& g* t( C
* 分页查询部门信息(其中一个部门有多个用户)  F' n( ]0 k$ [
*/
1 d' N) [+ j% q" p5 N0 }1 [' Xpublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
5 i! v  g) l. j    // 按条件查询部门信息
5 t- X7 \, l- n0 M. t    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
7 ]9 R3 m# ^0 Y5 U( a) q- l; I    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);8 D5 L6 T- [: @; Z1 E% v
    if (deptVoPage.getRecords().size() &gt; 0) {. |9 p! I2 C' k) U: _' [% y. e5 C1 N
        addUserInfo(deptVoPage);
3 u" ?- X3 ~4 X, {! b! W, N/ s2 ~* }, I    }
* G7 \( f0 v# D8 j+ d    return deptVoPage;( ], V! t1 y/ q& H
}1 M* L! N, }5 p9 g/ F5 f
</code></pre>
  v8 G6 O! h* C8 k: b<p>查询补充信息</p>( j- p1 ~$ O! x( j0 j% Q  ?: [
<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {) w* A6 ?5 j3 q) i5 {1 h9 V+ j2 S
    // 准备deptId方便批量查询用户信息
+ x8 Q5 j* @4 E  y5 b/ y5 {    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());+ }7 g: Z! T4 [, |2 b
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
1 D& `% h4 p+ r6 E    // 用批量deptId查询用户信息5 V8 \, M8 c8 r; i; l1 U& j2 g9 B! t
    List&lt;User&gt; users = userMapper.selectList(wrapper);
6 t) C- q2 p  ]/ l* G    // 重点:将用户按照deptId分组
5 H4 b/ h! [3 Z4 b& B    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));' {+ V- S% W# q, N" ~; j
    // 合并结果,构造Vo,添加集合列表
" t! [, T' F# f, G  d/ e& t8 g    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));( s4 x) m* B3 d( P
}; ?4 }: m3 _3 W  G0 N2 `+ e+ ?
</code></pre>  F% B, q" a) A2 H( t5 _1 z0 n
<h5 id="2理论分析-5">2、理论分析</h5>
) N2 o# A: r$ c+ c  G: s% @<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>; k8 z, k6 Q3 m3 q( k& [
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>' V/ d. g2 l6 o9 F
<h3 id="四多对多查询">四、多对多查询</h3>
: `  S' p2 a: S" L$ h& ], T, e9 I+ r1 I<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>3 w* i2 [, u! Q% T5 o' T4 {
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>, L! y( N0 t* n8 H
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
$ X. V3 \" l% F" |0 ]<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
$ R. N' I5 F5 ]4 z$ r: ~<h4 id="一查询单条记录-2">(一)查询单条记录</h4># ]( d) J: t  Q+ A- X4 \1 d  B
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>4 I+ m; q* v0 o3 W& v
<h5 id="1示例代码-6">1、示例代码</h5>
  ?; c' C2 B( [5 i( B% r<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
& }0 v2 }( x3 n& g: W6 f/ W    // 通过主键查询学生信息
) w' t5 E/ Q2 a    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
0 V* m- ~& m7 p6 H' _! P    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);$ [. Z0 s; M+ p; Q/ U5 q
    // 查询匹配关系
9 q# H5 d0 A/ ~1 W    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
8 t: G' v- a& c! p# Q    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());' T9 B9 {* k0 s- k. {
    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
9 M, r: s" `  b* ~+ F& ]        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
& k! O; v4 X+ u9 ?, x/ g0 m        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
" [- C9 C! _* h# m' D! l" E        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
$ J0 ?) _- A  H5 l/ G        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
( P% P6 m6 @- P+ \  c        studentVo.setSubList(subBoList);8 a8 s: X0 p, c& w/ s
    }+ A: c  g- C2 V% A6 H0 i. n
    return studentVo;; q9 I) Q8 d$ F" Z/ s) D. f
}
( P1 Y7 n( K% _9 Z4 B: m4 \</code></pre>
) i/ ?* Y! q- J  u' y<h5 id="2理论分析-6">2、理论分析</h5>. ~  R# D& V3 A! J/ g6 s
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
0 r: X2 @  @, }; F: x4 S) p" _<h4 id="二查询多条记录-2">(二)查询多条记录</h4># D# N7 _5 k2 F2 c* P
<h5 id="1示例代码-7">1、示例代码</h5>
/ W" l7 \( E; Q9 i* \3 ]$ U1 j; ~<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {& R% k( c+ |$ w+ u
    // 通过主键查询学生信息
( `3 C( z/ U; f: V; W1 l% b    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);% {* G( z7 U$ ^5 |
    // 批量查询学生ID
. F# q. J5 I3 j- X8 Y2 }6 [    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());4 j. ?7 v! m, [
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
  t- L+ R# l# A7 M2 \- v! @/ }* {    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
8 D- `# a! T7 q' w. d. E6 |' ^- ^    // 批量查询课程ID
1 ?2 t( v3 E( B7 _2 r$ v, W8 g8 f( O    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
6 A, C. F& O3 R" [0 j, |# c    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
; N1 Z  }: `& H9 h2 L, Y# q- t6 c( ~0 o        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
: q5 E" ], ?& y, m8 T; j! z        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
2 _3 h" t  j7 {2 ^) x% P        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);' D+ t; g$ t6 D- |3 j& Y( f( l
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));5 ~$ y) O. k3 c5 ]% N- ?
        for (StudentVo studentVo : studentVoList) {
' \* N/ a3 f4 G8 W            // 获取课程列表
$ e2 g7 o9 F) W4 k            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
! {$ o2 g8 ]- X( y            // 填充分数! `3 E7 W- x" p) q
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
3 F- `" _" B( U- h( b0 ~5 R2 s            studentVo.setSubList(list);
% h& w* l! @3 g        }
# p5 r" Y# d7 k- |/ t% C    }* p3 B, T7 E9 {+ X5 S- D! t$ c
    return studentVoList;) O' O9 G+ _. c
}
7 n4 x3 l5 x" G3 f0 m* H4 ]</code></pre>
, k7 u, R. h% Z# o<h5 id="2理论分析-7">2、理论分析</h5>6 `5 h. I) g! ?8 L$ q4 z6 t5 Y
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>5 V" F$ w/ m, L! H
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
, P* K* b9 P* B  C% W<h5 id="1示例代码-8">1、示例代码</h5>4 ~6 k0 g% ]7 N
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {' K  t' I+ J# `+ L) }6 p8 _
    // 通过主键查询学生信息& }4 C7 M( ?$ d3 Y, C8 `2 t. g
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);  ~# n  ?9 K$ D) C+ D: c
    // 批量查询学生ID
, b$ b  {' h- I$ W$ Z9 E8 N. x2 d    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
1 ~9 l, V. P$ ]* ]    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
3 u6 W+ t6 s' j" a4 c2 V0 z* u& {' g5 e    // 通过学生ID查询课程分数
, `; d* z1 V* z+ Y3 w4 A  B    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);  [9 i3 c& `. Z, Q7 S
    // 批量查询课程ID
* ~/ e: F5 M  O& m! o. @! R    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());; H% b2 l1 _  G% ^+ _" b
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
" ?) A( E. Q3 s% L, }        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
, O1 j$ p7 Y4 a7 `        // 学生ID查询课程ID组8 H' _& ]6 H0 k8 a7 Q* Y
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));3 o+ x) @/ V5 k% L4 x) m. }
" i% q2 t) t4 N! D( G6 _, ^! `
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
# D5 S# n( y& b) ]3 @1 d5 b9 i        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);4 ~7 h# M6 b) D( G; D  w3 t) P2 K
        for (StudentVo studentVo : studentVoPage.getRecords()) {
! c, ^0 I: n  W, `, U9 ^- y9 P            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
4 q, K5 N5 j! R2 ^7 R. p            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));5 x. e% ~/ [' w8 i( y- g5 P% @
            studentVo.setSubList(list);% A  m9 f# d0 D
        }
- W4 Q8 S- ~, p* S1 a    }
+ `) V4 ?  w! |( j' ~/ {    return studentVoPage;
$ o( k" g' v# n, R* z}
+ {; }% e: [) E/ D6 X</code></pre>  j: X4 H5 j1 O# T
<h5 id="2理论分析-8">2、理论分析</h5>
0 Q) G- D" Y( ]0 q! L2 ]<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
5 A: U. [5 \6 J/ i$ |<h3 id="五总结与拓展">五、总结与拓展</h3>5 C! m& W. @  E. [$ M
<h4 id="一总结">(一)总结</h4>% X0 n) T* @* t# }- H$ p" f
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
+ }& J9 X/ y9 C. b' D& |( r<ul>0 y# p" }- U2 @* |& ?0 t. }
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
1 m0 s$ U+ b4 h<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>- h- o. H$ S1 \+ G
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
4 u- b. c: l0 C8 i</ul>
, M* h; i2 e+ t& W8 y<h4 id="二拓展">(二)拓展</h4>
6 ?2 N# ~) O& G9 I0 |3 W<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
% F. W2 E' e' a& f! n<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
7 m) |3 m) i& h0 `1 H$ H$ q- J: i<ul>
# t. S; [7 |$ A<li>当数据量较大时,仍然具有稳定的查询效率</li>! G' n2 s5 u% C2 h
</ul>! c9 [6 E0 A" {& C* u
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>2 e3 Q, d: a* f. e, n  g
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
' ]2 ?. T6 @7 x- U% D9 X<ul>
" k! v6 I' K/ X8 [2 Q$ T<li>与二级缓存配合使用进一步提高查询效率</li>3 H! U, P: ]; y, y2 V
</ul>! k3 B: k; |5 Q, x# X0 c5 V
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>6 ?% h! S/ I5 N* f
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
$ T; ?' a! I7 ?' ~( f# B& K, ]
" T$ i; Z# O, Z) {$ \  o3 d" v- o0 q
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-8 09:42 , Processed in 0.066289 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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