飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7726

主题

7814

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
25508
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-11-1 06:15 , Processed in 0.077207 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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