飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8822

主题

8910

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
28796
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
+ [# t% ?3 P0 m, E3 }
<h3 id="一序言">一、序言</h3>
) N' Q! ^- p7 c" ]5 t4 I<h4 id="一背景内容">(一)背景内容</h4>  V8 y4 b" c5 s: O* t0 B
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
8 \9 A  e0 ^5 O' u# ^: E<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
) u7 z& W$ O  V- Z6 B4 W<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>% p) ?6 K( ]  b, k& ?6 q
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
) h7 b1 s8 d8 X; a5 j<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
) g- {- |: G9 p; {# e+ U7 v<h4 id="二场景说明">(二)场景说明</h4>
9 O. q4 V  W# V; K: v<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
% G0 I1 B, ^) G4 I- P<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >& m- U, ~$ c# r
<h4 id="三前期准备">(三)前期准备</h4>% z4 z$ P" k' e# \, F
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>0 \/ n9 |" b6 t4 G1 g7 J
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
( T9 f# e% h4 t<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>5 l5 C* K5 Z# o" \3 t  ]
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
7 L' p. Q! D& w) h/ U<h3 id="二一对一查询">二、一对一查询</h3>! j5 V& l* }) J4 g
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
/ E4 q  Y% k2 z- z3 x) y0 H0 k  b<h4 id="一查询单条记录">(一)查询单条记录</h4>
5 D0 g2 j* b( E3 ^<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
4 o  e0 B8 t8 W/ R4 I$ F<h5 id="1示例代码">1、示例代码</h5>
% b+ q9 c0 r  z; V6 f3 F5 I. v/ @6 r<pre><code class="language-java">/**( D/ w1 S7 }1 V
* 查询单个学生信息(一个学生对应一个部门)
% H* f5 K' ~* r6 d$ Y */
' B2 w' S: i7 \1 {. v, Xpublic UserVo getOneUser(Integer userId) {- \1 _) ]+ W0 T, Z1 i: z
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)" x2 p) X5 c% Y1 D7 _$ [
        .eq(User::getUserId, userId);! m& ?% |, R4 o3 f* j. p$ `" }4 U3 [9 M
    // 先查询用户信息
. L, u# {- f- D' P) j, }* X6 i. f    User user = userMapper.selectOne(wrapper);1 K! m; V' r8 q6 A
    // 转化为Vo/ p  @/ h; `% E, x( g' X+ \9 l; Y
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);3 L; t/ t# i4 L/ h0 f" W* |
    // 从其它表查询信息再封装到Vo
" y$ b6 ^) S6 b& N/ {( A8 n* G" {    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
# t2 i: J8 d4 v# e: k- V    return userVo;
0 X% C9 p* f8 \9 f1 h( C/ X# g}7 U6 j2 j2 h  t' u" B+ L
</code></pre># |- y9 k8 b: C$ }! K
<p>附属表信息补充</p>
) h% `+ u) l/ Z: x! z  m<pre><code class="language-java">/**
4 F- h/ J$ d- \$ V+ B * 补充部门名称信息
( [. `4 z1 b( |% G */
$ j" [; [! p* cprivate void addDetpNameInfo(UserVo userVo) {* h# z6 z6 |3 k5 q8 [/ p- H  l
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)9 X2 e3 G+ ]$ a, ?
        .eq(Dept::getDeptId, userVo.getDeptId());8 h7 P* B1 U( @  O. W
    Dept dept = deptMapper.selectOne(wrapper);
* k0 j& e$ d' ^. D7 `; G- |4 z3 |, m    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
4 y8 {- F; H# I) b}' X$ y/ ?! I9 M: p# a
</code></pre>
5 X2 x5 Z& E4 w  b  [$ Q<h5 id="2理论分析">2、理论分析</h5>
$ B# \- e) N7 \- m, P" e) s<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
; P) f1 B' p$ x& U; R6 n<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>0 l. n$ z( Y5 Y& l
<h4 id="二查询多条记录">(二)查询多条记录</h4>/ C$ k' g, C* ~" K
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>% k% _. t/ c, p: T
<h5 id="1示例代码-1">1、示例代码</h5>+ B7 X& v$ U% z6 B0 r, i' `: v
<pre><code class="language-java">/*** s5 c3 F( _9 U! d
* 批量查询学生信息(一个学生对应一个部门)* a  A( i7 R2 n1 M
*/
) F- C. d; M1 m$ Q, J- Dpublic List&lt;UserVo&gt; getUserByList() {
3 G+ v) w; O- A3 f* }4 `$ \+ e    // 先查询用户信息(表现形式为列表)$ E/ ]& T7 {% f8 l! v5 b' t7 c
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
  E# e* Y5 w6 j    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());) K% g; X# E% z9 c! ?, \" D3 [
    // 此步骤可以有多个
' C1 u# G: S6 k: ^. D( E8 s- O    addDeptNameInfo(userVos);
! s2 i, h3 V; P0 E( y& [. h3 B5 }    return userVos;
! V4 P5 ^' }, W}
/ s" x% q2 }+ q3 v4 J$ F8 \; r</code></pre>
( q! p1 l/ `* X' w<p>附属信息补充</p>
  _$ [: |/ B- v/ N* I- d<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {
6 C$ L+ V) L- _- w" L5 b    // 提取用户userId,方便批量查询5 G: P1 n2 h' I7 N' O9 ~
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());+ \7 j% R! N) s/ J0 `
    // 根据deptId查询deptName(查询前,先做非空判断)
% a: g% P4 [" j9 ^$ v4 y    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
9 o2 }( U0 J; }9 @8 L4 G3 _8 W% a    // 构造映射关系,方便匹配deptId与deptName
$ P, i7 z3 s, z. N1 {2 D4 m    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
* u: o2 [# z1 j) s3 f    // 封装Vo,并添加到集合中(关键内容)
* s; }$ Z) _1 F$ ]$ |    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));, L- [* o+ u' z, _
}
9 a. F9 ?2 I1 e3 Z9 n* Z+ i</code></pre>) F, a8 B- n) r9 J' F! d
<h5 id="2理论分析-1">2、理论分析</h5>
6 U+ u' Y1 N' Z- K7 d- C( I<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>+ d6 d" C* U" N" G9 F
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>( U- {0 O/ F/ @8 d/ Q4 y* {* S/ O
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
' _4 _( Y4 _4 _7 V; x<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>+ I1 s6 p; \6 i7 V+ F1 a
<h5 id="1示例代码-2">1、示例代码</h5>
0 @1 M$ _" ]: x2 P<pre><code class="language-java">/**  ], \3 T5 U1 S1 Z. J' m
* 分页查询学生信息(一个学生对应一个部门). h3 D2 S% o; r1 T
*/' ~6 A) X0 a6 U( a
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {  C  s% B* f, d5 R5 n& f3 Z
    // 先查询用户信息4 @9 q0 z/ ?; w" ~" X- a1 P
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());; q) O+ ]- W3 P( I9 M. h2 @" M
    // 初始化Vo/ V: _( `0 o) u+ t
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);- E, D* R; _/ G; p, u( O
    if (userVoPage.getRecords().size() &gt; 0) {1 l9 m, w0 B9 u+ g8 e) q# w. w1 J* n
        addDeptNameInfo(userVoPage);
. H2 c' J$ q6 r: w" x* I, u    }
, ]* V% B1 Q+ O" r0 O    return userVoPage;
4 T4 c3 ~' c; b}& z) L+ s7 W$ d4 f5 ?
</code></pre>5 G# p# ~$ `* [& t' y# w6 h; Q0 s
<p>查询补充信息</p>
& j; G  N8 u% N<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
: ^; P* @. `' q  L, z    // 提取用户userId,方便批量查询
- k' N* |- s9 p, @/ H2 B    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());2 |7 t6 Q/ \: ]" {. K. q
    // 根据deptId查询deptName
8 p5 B/ e/ E/ N/ B! G( F    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));( ]2 N5 D; L. a8 N0 A$ S  S6 R7 c
    // 构造映射关系,方便匹配deptId与deptName
  O+ O; j+ G* g3 Q5 G) g    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));- j4 @! x+ ^1 n! h) y: C
    // 将查询补充的信息添加到Vo中' X) Z# g) P, A" [) v+ q. h- ~5 ~/ ?
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
* k" I1 g4 Y9 n}
, \+ G! y/ r9 o/ \/ ]2 T</code></pre>
" T( Y( O/ y& N( _. t$ z( F<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
  n3 [( k' i1 J" c! ~<h5 id="2理论分析-2">2、理论分析</h5>
: Z5 o/ v; j* B: L7 q% a( o) W<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
5 P: O' P, U- a- U& _- G4 T<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
/ i  D! i9 e9 H' V: o9 U4 n8 w<h3 id="三一对多查询">三、一对多查询</h3>5 e$ [2 d8 c) J5 {: C. K4 k+ E
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
  r/ `/ ^: z1 g<h4 id="一查询单条记录-1">(一)查询单条记录</h4>0 i3 P6 ^0 u5 p# ]9 J$ e
<h5 id="1示例代码-3">1、示例代码</h5>' i& p4 ~9 @1 K6 N4 o; Z) W% Z# r
<pre><code class="language-java">/**, T# `2 ]9 j) e) t+ g
* 查询单个部门(其中一个部门有多个用户)
2 W8 n( j4 y7 A- c) I& H1 S */2 ?( X4 |8 v+ \$ r$ R$ r
public DeptVo getOneDept(Integer deptId) {
4 X/ ^5 D. ?9 m/ P    // 查询部门基础信息
) d" W4 k+ O! b    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);6 J0 D8 v" _) v5 I
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);, \2 f% h8 F1 _- K
    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);2 N5 i- j9 s% k3 j
    return deptVo;' ~7 X7 b* W: @# c1 Y
}! I3 ?0 T" s0 O. X& m
</code></pre>
" `+ d8 w7 w( }# ?6 F# D8 t0 K6 T) g<p>补充附加信息</p>
) }* b. M/ ~" c4 G+ \( f5 z4 K<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {0 v' y( x& \1 }7 [! {
    // 根据部门deptId查询学生列表7 R! H1 D* x8 f2 ], y8 Y
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
' `' `4 _: P! T    List&lt;User&gt; users = userMapper.selectList(wrapper);
5 l3 ?8 C9 @7 t$ z    deptVo.setUsers(users);2 {, m# f) l' l: }& Z, d  x4 B$ I  K" z
}& y: r- i/ r+ ^: `& o/ [6 [
</code></pre># f  j$ v/ |- n8 B: c6 C
<h5 id="2理论分析-3">2、理论分析</h5>3 t! I" W! u! L% d/ q1 k
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>5 z# ]& p$ z) M1 w0 P7 i- S
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>  |; V  j, k3 x5 S
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
: X, ]  K7 x8 f6 Z" a# |% T<h5 id="1示例代码-4">1、示例代码</h5>4 s4 C' \0 j9 K  R3 D% B" A5 x
<pre><code class="language-java">/**+ a/ K; S$ d- g7 J# R# ]7 E7 j% I
* 查询多个部门(其中一个部门有多个用户)
& V! J/ X  X; ?1 w */$ S; o$ ?/ ]& v' ?9 A! l
public List&lt;DeptVo&gt; getDeptByList() {) a! m1 x+ T. L+ j
    // 按条件查询部门信息* f4 p) d4 ~+ O0 K3 a
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());* N$ R" |5 z! ]: d
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());4 T- u3 `$ q" E' I6 B8 v
    if (deptVos.size() &gt; 0) {, U# O. e% W: x8 R- h! D- U8 {7 t# Y
        addUserInfo(deptVos);
8 S/ u/ Y, [) y8 j    }! R2 f4 _5 z! T" e5 l% ]( G9 Y! b- {
    return deptVos;: g5 h% \2 I" R5 r9 `8 \( Z" r
}% E/ @5 {" `3 F& s9 ~, D0 h
</code></pre>
, a$ o: d/ j, w% q/ S0 g! i<p>补充附加信息</p>
6 n9 t7 ?- K0 V. ]<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
5 A2 R6 K4 r8 g    // 准备deptId方便批量查询用户信息& B/ x1 ^' A& a" b7 ^  L7 m
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
3 g4 K! T" n8 k! C    // 用批量deptId查询用户信息' S% D! k* e8 H% {. ]
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));) o2 f7 Z/ \. s, a4 E5 @: z' H8 n' J
    // 重点:将用户按照deptId分组3 K0 n. R1 V" }6 [4 r+ H( R
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));! O: V1 s( F! `) b4 P; }/ O
    // 合并结果,构造Vo,添加集合列表) h: @. r+ r3 V& k
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
( Z: R2 R7 D/ S: f}
! K1 I4 E/ Y" M- D+ ~+ x</code></pre>" s: _3 y7 b: w4 H; M
<h5 id="2理论分析-4">2、理论分析</h5>( c. w/ v2 ]* J
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
$ ~- W( s( i3 K<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
: p7 y! ]( \9 v<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
1 ?/ }# o7 o; \<h5 id="1示例代码-5">1、示例代码</h5>
) l4 G+ I2 M! q6 s# n4 v* L- K<pre><code class="language-java">/**; y' L# u, E* W/ n3 ?" b
* 分页查询部门信息(其中一个部门有多个用户)! l7 j: F, m$ A; W7 }1 `/ [: n
*/! r* C  M/ Y1 A/ @( V+ Z0 t3 C
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
% m, [1 x. k5 T. [  L. K    // 按条件查询部门信息
/ s+ w# w. F. `. |: v    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
7 j& K3 i' d8 X* ], I    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);2 Z) Q1 Y/ x5 ^+ Q; D: W
    if (deptVoPage.getRecords().size() &gt; 0) {
5 i( U' F0 O# {4 l2 d        addUserInfo(deptVoPage);4 `( E* G. Y  \5 P* B
    }( F2 q$ B; y* \2 ], l
    return deptVoPage;$ p3 ?! o- L+ _- `! ]5 K
}
$ K- O/ O1 a8 `6 o7 Y5 g</code></pre>
  x4 d$ ^& t% N5 [+ H. [/ a<p>查询补充信息</p>' p7 @  x# y# r# y: }
<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
- A9 N- v2 T4 N; ?$ O    // 准备deptId方便批量查询用户信息
5 b4 \( A6 [+ r5 K% `2 p' \! v    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());) ^3 F, r, ?( Z& L, r- c: m
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
. ^: ]2 f6 U/ `# ~' j6 i    // 用批量deptId查询用户信息, @7 R+ E# r; G* L6 F0 E2 ~5 n
    List&lt;User&gt; users = userMapper.selectList(wrapper);
7 g& R4 N+ S8 @: y8 g+ p    // 重点:将用户按照deptId分组
5 N7 {  o6 _+ ~. T8 [0 T- g1 O$ N6 t    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));( o/ t* @; _4 M
    // 合并结果,构造Vo,添加集合列表5 L6 R  p% u' e- }1 J
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
8 k! ]# x% C9 j0 L}
* q6 g% I7 _9 K. ~</code></pre>! h5 s$ S) L) a/ h( ~) K. Y
<h5 id="2理论分析-5">2、理论分析</h5>2 p! B: g; D0 t+ T
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
  P' o* A, Q9 }  }2 Y1 V<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
- J  F9 v! |% k% G# w8 D. t, c<h3 id="四多对多查询">四、多对多查询</h3>' V! C" _# I, v. N* R
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
* L: a0 r8 O2 |$ x* l<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>6 y; X" ~" @% ^
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
4 |5 [* W/ _3 B& Y5 E5 r<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >. S; G' w  l. k4 C
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>( ?% R" F7 E4 i  A- f' k& ?
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>% M% ?0 x3 ?' e. Y$ }
<h5 id="1示例代码-6">1、示例代码</h5>/ y7 X1 F7 m9 Q$ k$ V
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
) ~& R6 @' B/ z; L1 p0 }    // 通过主键查询学生信息
+ d8 A1 x- V6 W3 Q: b/ n    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
& j( s6 |: ?* n$ E! _    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);8 H9 M0 e6 a, X9 U
    // 查询匹配关系! l  u- k1 q9 X
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
& r8 B. m( N/ g  M% v$ |    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
/ b6 F- Y" o7 U, M    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
' [. S0 o: C3 ]' k        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));' W% }& J9 x5 H: ]
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
5 e  g  j: s# h9 j* C6 y        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);' H% S5 G5 M# f; C1 p) v/ w
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
. O$ e" q) s9 @6 ?, d7 V        studentVo.setSubList(subBoList);
4 E3 I" W; _; W  b: U; |) ~& q    }+ o5 [& m9 \! H( C. l# m
    return studentVo;1 i0 t  Y0 I( K: ]/ m/ g" c; W
}
& y, p# A. A1 H( O8 b+ G! `5 L</code></pre>1 j! D% ~# @# ~+ ?" f* M
<h5 id="2理论分析-6">2、理论分析</h5>' }. x" I! g! j9 M+ D# h8 b9 o
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
0 p  \' I0 X0 j  `1 h( @) s<h4 id="二查询多条记录-2">(二)查询多条记录</h4>" ]% @. N/ Q( {/ X: r" f
<h5 id="1示例代码-7">1、示例代码</h5>
  H& K" X0 M, a# F! i" V<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
9 @3 ^) `) Z6 l# _1 E' T$ r/ O% |    // 通过主键查询学生信息
8 b$ x+ ?! P# S. n# S4 @    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
# D- {" K# ~. j# J$ E3 _    // 批量查询学生ID
2 m, N7 [- g; F% o8 |  L    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
, A/ P# d7 P- Q0 j! D& K$ H; F& c$ d    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
3 e+ ~! T8 J) b7 X    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
5 ?6 P1 V3 M4 n' G& C3 k! T- w4 i, A    // 批量查询课程ID
! A" t4 z7 p) i8 ?" V  W5 |# I    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());5 @( i8 i5 N' R9 b
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
9 B9 Z! q: N0 {: H# V# h; }7 a        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
0 J1 E. m+ Z; ?7 ^7 J4 f' B        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
5 K4 ]  l* M: V0 Q        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);: w* w0 H2 _6 t- N) a$ Z
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
( |0 E8 t6 F% Z( a2 x/ l/ |  i        for (StudentVo studentVo : studentVoList) {: t$ a8 _0 S% m, n: o9 `. R
            // 获取课程列表7 R4 {$ {6 n. T# o: x, G
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
- w9 C* E. c8 F( {1 b$ d4 ~2 g' G: ]            // 填充分数
2 T3 v" R& e8 b/ b/ Q            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));8 a- |0 {) |' P7 ?
            studentVo.setSubList(list);
3 V# N4 e+ V+ I' i: w1 ]0 t        }; e$ ]  _/ F7 }# ^
    }
4 i9 g& w2 D; Q) ?9 S) G& a6 j    return studentVoList;
2 B/ e; p9 R' {4 V- }$ i}
1 Y- \' T9 U8 p- a* r, K</code></pre>, i: ~1 |; q! ~  \, @' N( q; M
<h5 id="2理论分析-7">2、理论分析</h5>
) D% d, I& y4 v% k6 c$ z<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>9 q( `5 W* l' @6 W* I) }
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
) m9 E" T  z1 X9 a+ X<h5 id="1示例代码-8">1、示例代码</h5>! }; S' A3 Z7 a2 ~  ^1 o/ ~% Y
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {  h2 \4 g: ^/ g- ?! D: A
    // 通过主键查询学生信息( y8 A7 u5 H/ Q& c; o- w" g5 {
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
2 f0 E% L& Q0 H' n1 U    // 批量查询学生ID7 G% B- o6 x* p' o& i8 v; u
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
- \5 }9 ^& ~/ T2 X    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);) A( f0 W- }0 b& m6 Z; U
    // 通过学生ID查询课程分数7 K6 F) Z" _0 N  j, ]; V
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);  }4 e" G9 s. Q" d
    // 批量查询课程ID6 y5 S* @( H) I5 W, N3 K+ w
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());& F5 m, ^6 U4 \
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {8 P7 Q/ k$ a6 U/ }* i
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
9 M# s' N, c: q: e4 V; v        // 学生ID查询课程ID组
6 ~! B1 Z) J  M& ?) F% W1 \8 A        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));. ^0 @/ a5 h5 B  _% A, N

5 {+ s7 w: V, ]0 M        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
* m! K7 |) x7 K& f        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);: o, m1 `0 L# ^
        for (StudentVo studentVo : studentVoPage.getRecords()) {6 z+ B, G9 r% b
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));$ y8 Q( {" Y8 V8 Z' n: o- k0 N0 C
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));& ~5 d0 G' V$ X' p1 s: \9 G6 l' W
            studentVo.setSubList(list);! i! d# C* g+ p$ d
        }% u- x$ S4 ~9 D, y4 Q: _- E0 R$ m
    }( o2 y+ a/ R. l
    return studentVoPage;6 R. Q8 c+ M3 D5 U( \8 c
}
4 Q/ k+ l( J4 |5 u6 v! L</code></pre>+ u3 I/ _" A1 o2 a
<h5 id="2理论分析-8">2、理论分析</h5>
' @2 Q3 L& a* A; h# _. [8 P+ n. g4 Z<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
$ h$ R+ Q1 K# ?$ s/ p' [2 Q3 G2 Q: R4 B<h3 id="五总结与拓展">五、总结与拓展</h3>7 C& [( {5 ]7 U. P
<h4 id="一总结">(一)总结</h4>
1 K' {3 l: X/ C( x<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>4 L4 W5 w' [! C% x
<ul>
9 m4 j- B( H3 c5 Y; M9 U4 _<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>9 s* |8 S2 Q2 Z+ H
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>" j) n+ F* y% G6 r4 x" I
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>' Y. R$ A8 _1 s, N- M
</ul>/ J4 b% v" _; t$ _5 m. z
<h4 id="二拓展">(二)拓展</h4>2 e" k- e, ?3 n* s, E0 J  ]
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>% x$ e/ _# ?: F/ M. B" {0 z
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
/ R$ }# N/ \+ d- T/ ?& w) b# p1 X+ T<ul>
8 s' R7 Z' l; E7 L3 r4 ~<li>当数据量较大时,仍然具有稳定的查询效率</li>
' ]4 f1 b+ k: S% Q- L" K3 ?8 `</ul>4 V7 ?! b% @* w) m+ t! H; L
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
! a' N4 U4 Z% C; t8 R7 \<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
# J- p  ~+ p9 x- ?<ul>2 ?% R; }6 e2 |) `, ~
<li>与二级缓存配合使用进一步提高查询效率</li>
- o5 K) J* ?4 b1 _  f; }6 k</ul>9 o2 d  C* \  h" T- g3 C8 k) p
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p># t; z( c2 i9 k' O. C
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
* q; K6 Z2 B/ s! D5 I$ y4 ?% n
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-5-28 05:05 , Processed in 0.067213 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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