飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7726

主题

7814

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
25508
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
( y6 r# I: o7 S3 @( r
<h3 id="一序言">一、序言</h3>- m4 I9 y; _& U3 w: u
<h4 id="一背景内容">(一)背景内容</h4>, I" y- p  v) {; T$ S* \* V
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>: J1 h2 t7 S2 x0 p" r1 t
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>5 }% M* T' C7 @' n6 b' ~; z: ]: S
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>' L6 A3 }% C3 I3 f
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>. v( }. j. e  V5 i1 m- \
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
# w; ?( f- p) u1 M% M<h4 id="二场景说明">(二)场景说明</h4>
- ]% O# j1 Q- x6 c<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>  |0 u' f) h. m% w  e' W
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >" D  U9 v5 m1 C4 ^) O0 A
<h4 id="三前期准备">(三)前期准备</h4>
8 q9 E+ O8 g7 j6 }) V<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
  L* A+ H% i- ]/ G. z+ ^<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >! j$ L3 f0 {. X* ~# A
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>% N! Q, V3 H+ C% r; L/ _0 ~( W
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>: j  i/ z. z- C2 D
<h3 id="二一对一查询">二、一对一查询</h3>
7 G& {# R4 r, j0 V" }8 ?<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>. Q3 R8 h8 z: v
<h4 id="一查询单条记录">(一)查询单条记录</h4>9 P2 B; @$ t, k1 b8 p4 b
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
3 l0 x4 K- e; D/ h% I) ?% \/ e) }# x<h5 id="1示例代码">1、示例代码</h5>
; n& r; o" M2 \6 |' l4 _# c+ o<pre><code class="language-java">/**
. {' u0 G" k7 a+ L0 x6 O * 查询单个学生信息(一个学生对应一个部门)  q8 h0 S3 f0 g" {
*/
* C1 n; r7 \3 H, g2 rpublic UserVo getOneUser(Integer userId) {0 U, h9 }" A1 s" Z/ u
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)6 `2 u' I1 x' j, y, p0 u9 }
        .eq(User::getUserId, userId);- G" M+ L1 F6 R0 T) ~8 ^: F
    // 先查询用户信息% L) P4 g7 }. d7 e) c
    User user = userMapper.selectOne(wrapper);  g* `9 y& p) L- n
    // 转化为Vo
" _- d3 }' R7 {8 t7 ^    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
  C6 u- D! F: z8 O* S, q- D) U# p    // 从其它表查询信息再封装到Vo8 u0 r' S% m- B" _0 x& @* b
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
1 L( j, w: E3 C0 F1 q# o    return userVo;
: s/ J/ p. u% p  s) x- A- ?}
$ t/ q9 |- r9 d  d% k1 ]</code></pre>4 O( K, N% d& e2 y( k
<p>附属表信息补充</p>
" m; O1 ^# O& }7 J# d<pre><code class="language-java">/**
8 G! Q* r. ~3 }2 s* q * 补充部门名称信息; @8 Z+ h. Z$ x) Z% X
*/
1 Z) c  ]' a: t3 C: z: ^private void addDetpNameInfo(UserVo userVo) {
5 ^' s- s" T- W1 D" u9 F* s4 u    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)# V; a4 l+ v0 A5 A( s) a' D4 Y
        .eq(Dept::getDeptId, userVo.getDeptId());
% I& v  B8 {2 |* ^    Dept dept = deptMapper.selectOne(wrapper);+ x4 k' X3 F; y" {2 d7 X4 Z6 E3 S
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
: Q- h' d0 z, n) @, O2 m: F}5 L" C1 a$ T+ m9 c
</code></pre>$ R1 \: x- U8 n) |6 O# b9 r, ]% G/ F; U
<h5 id="2理论分析">2、理论分析</h5>& @. W$ F3 m$ A* Z$ c2 z- F
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
  U* C) N: d1 g<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
1 }1 a: v5 t' t7 u# ]* l5 D8 W<h4 id="二查询多条记录">(二)查询多条记录</h4>
* t" ?7 [$ q  a" n<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>8 B. G$ [" M- V1 ~! A
<h5 id="1示例代码-1">1、示例代码</h5>
0 o$ X8 @6 i9 h9 ]& Y" ~1 B2 S<pre><code class="language-java">/**4 H7 d3 U/ i- K$ ]2 Y/ x7 W! K
* 批量查询学生信息(一个学生对应一个部门)
, Y5 J- f' c6 ~7 n% n+ {5 U */* }. `4 B1 Y3 ^8 ]3 w
public List&lt;UserVo&gt; getUserByList() {% ]3 @8 u/ h+ ~0 k
    // 先查询用户信息(表现形式为列表)
1 }0 t" z7 Z* |  H    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
5 k$ z% z' x/ K! j  W0 f- }# t9 W    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
2 x! `7 W9 B' t' v6 V5 l    // 此步骤可以有多个. p6 x# n; W. p/ P  z. h- X
    addDeptNameInfo(userVos);0 H; J+ `/ O5 f, U
    return userVos;
* X1 \9 O( g: k3 W* ~9 h% V}
; u7 ~7 k1 Y1 i</code></pre>
( n6 _  H5 ^+ z' k: `: N  F<p>附属信息补充</p>
3 K4 O3 F- |" o<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {. [( i1 [% N7 T. i' J+ k
    // 提取用户userId,方便批量查询
, u# w( w/ ?: x( k    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
0 G! n' K2 c% C$ S" x    // 根据deptId查询deptName(查询前,先做非空判断)
# T# `( t, t% l8 r+ a5 C/ i    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));" k9 N$ s4 u) R( a, g" Q
    // 构造映射关系,方便匹配deptId与deptName- M: w9 T2 y, F8 \  [( b
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));# Z* [% o" R6 Z& G: B0 d
    // 封装Vo,并添加到集合中(关键内容)1 X9 q5 C: K: i; n2 Q
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));+ w# e- F7 S% L; Q7 Q& b
}( Y$ w- d7 c, X, R  x$ k
</code></pre>7 I3 o0 E* u% d8 ?" O! f9 B
<h5 id="2理论分析-1">2、理论分析</h5>! n8 |3 Z% `: h- n" _2 q
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>) c' O8 \2 {3 f& w2 c& {/ K  @
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
+ h% K) N# w* g) C; n5 \4 b<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>; Y) T9 D' i" c( Z$ B
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
$ o- _: ^1 `8 f( v<h5 id="1示例代码-2">1、示例代码</h5>
- ^1 Y' b4 V2 n. E& m& s<pre><code class="language-java">/**. w2 {+ R, N3 ^
* 分页查询学生信息(一个学生对应一个部门)$ J$ @$ C5 n  e. m: }
*/
- J$ [7 O# A" C% w( {; {6 U9 Mpublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {7 k/ W) S$ J" l6 j' R$ m
    // 先查询用户信息6 q. @* P* j8 X- R7 G
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());/ G4 H2 m/ w! [
    // 初始化Vo$ }7 P8 Z6 P0 Q7 Y$ |2 y# Z, [
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);3 i& M9 j& I: q' N
    if (userVoPage.getRecords().size() &gt; 0) {
/ s, F1 e" s8 X  h        addDeptNameInfo(userVoPage);
$ u" H6 l; l- p% M    }
0 R4 R7 e( q/ X" b$ R  G  i    return userVoPage;& u7 m, d6 ^( N
}2 w3 m: |4 h8 e8 `
</code></pre>
, [. O) @7 L; T# I" f<p>查询补充信息</p>
# G3 n7 ~% [/ o# q<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
0 N+ V8 P, P, _# H1 Z3 F    // 提取用户userId,方便批量查询
. o, Q& E6 k  J" w* @    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());1 I6 H. Q4 Y/ [' L/ h
    // 根据deptId查询deptName* T5 n/ k, v& U# Q3 ^" @7 a
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));: H% a( d8 b2 |9 N$ _6 j. H" }4 S* W
    // 构造映射关系,方便匹配deptId与deptName6 M7 k0 k; j3 ]9 r$ h3 P+ [
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
, D8 k6 o, }5 A3 w. v4 V5 T    // 将查询补充的信息添加到Vo中! d* v$ J2 j9 J8 @' {  h
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
, E2 z" Y1 C! O9 F. p  @0 U2 P, b/ V}
# @# J7 }: I6 V% T8 E</code></pre># l2 U' Q0 o- k8 n6 ~
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>% ^# m! }4 D+ W* B. ^6 X
<h5 id="2理论分析-2">2、理论分析</h5>9 ?; x) P( i% o7 Z5 l8 t
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>2 {) E2 _. {1 f7 L
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
1 }4 X+ ~3 x1 _3 U1 n$ O% H<h3 id="三一对多查询">三、一对多查询</h3>6 @% S  F  j3 _. D
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
) d/ r" o0 v- E4 N: ]; I1 h<h4 id="一查询单条记录-1">(一)查询单条记录</h4>& \: a5 ~* {$ y8 Z; \5 H" a* T
<h5 id="1示例代码-3">1、示例代码</h5>2 Q6 P; t; n) q( J' o( h3 t
<pre><code class="language-java">/**0 ]3 a8 [4 D7 F2 \. ^( z- j
* 查询单个部门(其中一个部门有多个用户)! H$ v% b! ?9 H4 a% p, _, E! n
*/
8 Z3 d3 l2 |; f. _4 N+ @" N% Spublic DeptVo getOneDept(Integer deptId) {
( G9 X. h: d0 F9 w    // 查询部门基础信息
* }) E/ w+ T3 N7 ^" w: L2 y    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);# g7 |; A+ m1 e) ?2 v
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);& Z9 F1 W. f) y# s4 M
    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
1 Q" f# N( Y8 d& d    return deptVo;5 b! v* j1 \5 u. x9 G* A. ]& j
}6 g# q' ~: n, q2 O8 N: E' a
</code></pre>. }2 B' P) x$ i+ |' ^6 Q/ o
<p>补充附加信息</p>' P; Z3 Q# W$ ]
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {: f! q) F6 @1 x9 q
    // 根据部门deptId查询学生列表8 @4 w$ y. r% K" q5 F; ^( \* |" x
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
. A& F- ]/ A# d4 Z    List&lt;User&gt; users = userMapper.selectList(wrapper);
! Z, A1 U. y2 X* t    deptVo.setUsers(users);
+ x3 B) v5 H2 f0 c- x0 w8 k: s}4 B; G3 k; G( h* @/ x9 ^. k7 ?  r
</code></pre>
1 C8 Z9 ^- X0 {; W5 G<h5 id="2理论分析-3">2、理论分析</h5>
/ J! H+ c* e2 Y2 c6 L<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>" K7 s. [4 f% r, [- q7 D
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
4 Z, C. N( {# n3 K<h4 id="二查询多条记录-1">(二)查询多条记录</h4>4 b- A4 @# G4 k+ [& j. p
<h5 id="1示例代码-4">1、示例代码</h5>9 [  T: ~2 t# R" U+ Y  b
<pre><code class="language-java">/**
" f" K% [( \; U0 L5 ]9 T, h. X * 查询多个部门(其中一个部门有多个用户)( Y' Z; c7 n' [' T# E) ~+ {9 ?
*/
3 Y4 d7 \' R# z7 G8 c6 [0 g$ L% w3 V9 opublic List&lt;DeptVo&gt; getDeptByList() {
  X, c* T2 C( U- A. P    // 按条件查询部门信息1 H' i3 \0 E$ Q0 y
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());+ M( W% t; [, r. w6 c7 W  N; D
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
3 _& r; F# c( o1 ^. T9 J    if (deptVos.size() &gt; 0) {* k8 @* l$ p8 L% n% b, H
        addUserInfo(deptVos);2 a6 U7 P9 H6 G0 t5 }
    }
9 I* {6 {" c* `# B* q. z$ G1 w1 ?    return deptVos;
4 K' g* ]8 J1 A* _% `}
/ e+ H" r8 m( E; u  ?0 B1 ^  J& H0 J</code></pre>
& W! c% G: B8 L8 N/ @0 s! t<p>补充附加信息</p>3 ~) A8 m0 P+ R. t/ C
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {+ X3 a* r% D# l, H3 T5 _
    // 准备deptId方便批量查询用户信息2 m& t" k0 p* ~) ], J4 T
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());/ R" f: D& ~" {1 _) p) i1 ^
    // 用批量deptId查询用户信息
* R# l# C- s# B, z4 L    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
! \) b8 k4 j4 U  f+ [4 i5 e$ n    // 重点:将用户按照deptId分组
7 h% V6 u# P7 z( c, n) p    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
& W% z3 y8 r" J6 U$ w& Z: Z4 T    // 合并结果,构造Vo,添加集合列表
; R7 K/ [- D7 T2 f9 o" ]# h" c    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));# A- W: \* D6 u2 u# l4 m. U
}
+ A, x1 g# _# k1 I; q</code></pre>. H/ O2 I9 d& V2 t) K6 Y
<h5 id="2理论分析-4">2、理论分析</h5>
3 k. u# V' q3 o* g* U2 B" B2 r( |<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>- I! Z: i4 u% H6 b2 F% \# ]
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>7 F9 d. D( z) Y- E+ {
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
- b; x  Z2 d, b" B<h5 id="1示例代码-5">1、示例代码</h5>4 ]$ P0 H$ V& F6 J; @
<pre><code class="language-java">/*** m- [# }& D& D- Y# C- ~7 e% B/ g" x
* 分页查询部门信息(其中一个部门有多个用户)
  p; n% o, b5 f0 f7 p. D+ i  s */
* d2 ?2 U" \1 O" i4 I8 tpublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {  y) [) m& }* w$ B
    // 按条件查询部门信息; _( K# m, O/ ]3 G+ D
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
2 y: Y. ^" S' N8 m- a0 e4 t8 h    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);% H$ _5 B; _, V0 r  c  a9 P
    if (deptVoPage.getRecords().size() &gt; 0) {
) @" }. r8 r" @6 V7 o/ i, J6 a        addUserInfo(deptVoPage);
5 y- h, ^- b. I' ~9 J1 d8 O    }+ W5 f. n' }7 g+ M
    return deptVoPage;
, t  G, ~+ [7 r8 j}( }! h/ H$ N) n4 F2 ^
</code></pre>
2 |+ j' ]) o5 L<p>查询补充信息</p>
8 c$ b# `; ?% F* V  m<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
+ e& k* c& `9 v! z    // 准备deptId方便批量查询用户信息2 h, s) N( V; X9 m
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
& T$ G. L& v6 I) m2 f$ l0 E2 E    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
# u/ s8 \9 x6 ?( S- v    // 用批量deptId查询用户信息: u0 t5 v. C' I# x& t; ~
    List&lt;User&gt; users = userMapper.selectList(wrapper);
$ a: V' }% }( X    // 重点:将用户按照deptId分组
7 S* c* Q; N0 S9 w    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
2 c+ D& ~5 W$ s" u# [' l* }1 B    // 合并结果,构造Vo,添加集合列表
. g: S' n+ J% Q' c  C! _    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
, ^! Q& f; U1 n# w: i1 g2 R  n}
3 J- O7 T0 b( h- l</code></pre>; r- ^9 V& F% P  T4 W# W
<h5 id="2理论分析-5">2、理论分析</h5>
7 k6 |9 d6 @$ H; T0 o3 @<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>& Y2 Y9 K" t! [( ~: h8 F2 X
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>* L6 k9 R7 Q* m$ H( l
<h3 id="四多对多查询">四、多对多查询</h3>0 W6 e# A5 R! E2 C: e9 A% B' G
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
' L- [4 T4 n2 i" Z9 L<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>2 o6 {4 q" H& o+ X5 I( ~  O
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
  ~2 o9 q9 L  M. w<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >. t0 o1 F' l3 c, r. D
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>9 B' |1 w6 a& ^, ^2 ~3 f8 z# V8 k
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>0 }% q9 J3 E& D$ [
<h5 id="1示例代码-6">1、示例代码</h5>
$ ~1 {" L1 K- W5 ?  c1 U<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
4 X- D, M" `! ~3 X    // 通过主键查询学生信息. E  w4 q/ n, o
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
3 f* P+ I  v% E    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
: |6 U  ], |5 g# W  |. M    // 查询匹配关系
9 F2 ^( x8 s3 W$ v6 w3 y    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);4 L8 m" I1 A( S/ t9 W- i# R2 i
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
5 b1 G- ]' S3 X2 U7 c/ w    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
. y% U1 L5 f5 V4 B' C' D7 Q9 B% E        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));& k/ t* l1 t/ q* ~. T5 r
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
1 I7 D# R8 _  P        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);  Y( v6 B; M6 u$ H8 l7 ~# a$ _; w& E
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
) U1 |2 k* k4 w; r7 M6 t! x        studentVo.setSubList(subBoList);. _7 ]: r% O  s* m7 T, U
    }( v+ I; ~& D* ^* n& F( f) g8 j' b
    return studentVo;
+ p$ X* R9 q5 W( R8 I}3 x$ |" g5 m9 O
</code></pre>; ^, T  z" {& R9 {4 ^; ~
<h5 id="2理论分析-6">2、理论分析</h5># M( N9 L: R) @
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>: [' P" {( ^. \$ \
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>: s3 h  r4 q2 @
<h5 id="1示例代码-7">1、示例代码</h5>
! Q: O. H0 C. j" B* G6 Z<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {* E5 k; G- s; N
    // 通过主键查询学生信息
" B5 m. a$ v, @2 e) ?0 r    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);% `7 `' Y: t% Y4 v1 _
    // 批量查询学生ID
; q( e. c% c9 a. G    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());. {0 x- O6 K, y2 l2 x/ \0 a- g% B3 y
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);/ h3 c# q" f6 K1 L
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);* G6 S+ I$ E. {, V
    // 批量查询课程ID$ ~$ G4 o& N; \  |- b, I
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
+ _$ p- S( U' O    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {3 T. L% M# K# w8 c. }8 w) p
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);& `! x7 k' s9 O/ P
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));* d6 c$ N6 g! F7 H4 a8 G# E
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);! q  j# O( W( B
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));, C3 L- n# @4 @, Y( l: \" @
        for (StudentVo studentVo : studentVoList) {
8 ^/ ?3 p: K1 F4 o- Z/ G& H            // 获取课程列表
  U& ?1 t. G8 a- N            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
( V+ h, `3 n& g) i2 R2 e            // 填充分数
$ |( P; r( K1 c$ f. [2 q            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));2 |0 R& A0 O: u* E# c. g* Q1 ^
            studentVo.setSubList(list);
  q* h) F' m# R4 o* q        }5 u8 ^) v  Q+ P
    }
1 h: E7 x1 \7 X) b    return studentVoList;
) R; X  ?0 M2 l}
" L# K% M. C7 x1 q" e/ ^& c</code></pre>
+ m6 r" n4 Q4 k9 [; f: V<h5 id="2理论分析-7">2、理论分析</h5>+ H! L0 r0 m( v3 X# m" X$ Y% G
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
" h' N9 a# f5 K+ x( j6 ~: Q, d& `<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>$ }9 ~6 @- H% ~/ x
<h5 id="1示例代码-8">1、示例代码</h5>1 L) J# @" d) o+ K; ?# _
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
5 p! F& l# s6 Q) s8 F/ Y3 B    // 通过主键查询学生信息( O) a! {% [. ?* L" n5 d9 g
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);. r0 }' H+ j3 v
    // 批量查询学生ID
7 S" M0 e0 ~0 J, ?- g- p    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());0 j+ k- L8 g& s. N' C' ?
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
8 i! E' |5 x9 R) Y9 @% Q    // 通过学生ID查询课程分数
- |* t8 S6 w6 X# e2 X3 A6 y; f3 L( Z8 j    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);3 \' ^6 P1 j* ]# o- i/ P
    // 批量查询课程ID2 D3 i: h1 @+ ?! @
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
$ [& g" v7 _% P/ t2 Y3 Z    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
) P6 i. q6 j$ P1 I        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
( |  [3 J3 I) d6 e        // 学生ID查询课程ID组" o& @# b6 }7 E
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));( Q' A9 J7 N9 D1 u

' y) H0 b7 Q5 n% W+ W* `        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));& |- h3 I% g3 Y0 K& v/ \# I6 v; Z
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);4 H8 S! N8 O) _  M( o# j
        for (StudentVo studentVo : studentVoPage.getRecords()) {& f  p2 a( E1 |' E) F8 B5 o! o
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
9 W9 O7 k( P1 P0 K# A            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
% G) ]3 I7 y4 d7 y            studentVo.setSubList(list);! B+ n2 a$ P! a  f3 S* z$ ~
        }) C* u$ }2 ^! \* [5 e; b
    }
3 ^8 c1 e  r6 x. c    return studentVoPage;/ u- ]  {; e/ }
}
$ c1 h3 Z, }  P; {& Z9 ~</code></pre>- l3 ]3 M  |' @. A2 Z* F- I
<h5 id="2理论分析-8">2、理论分析</h5>
5 o) U2 t6 P" y* ^2 U; W<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
% x) j! g3 t% `9 N<h3 id="五总结与拓展">五、总结与拓展</h3>% v! }9 I; `& z+ A
<h4 id="一总结">(一)总结</h4>
" q2 ]* m, ?* s, s* S<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
6 \& E! b2 B$ ^<ul>
! [. l+ |2 g/ m6 I% r3 e<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>0 a) w& w5 r9 M, j
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
& a  |! @" F& H4 m<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
1 E. v0 j' L% d' {3 T0 \' F, W4 h</ul>
% O/ F2 g' Y) p3 D+ O( R<h4 id="二拓展">(二)拓展</h4>
  k, I7 A/ f3 _8 G& }<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>8 s' T! @( J# l
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
; w, z7 G9 ~! z# h! D3 }8 A$ ~<ul>
3 E6 ~  p8 |0 g, \4 b. d% R9 Y<li>当数据量较大时,仍然具有稳定的查询效率</li>/ k7 V: g) b9 N2 z: t( s. l
</ul>9 Z/ L- Z& X; _  e
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
2 i7 j) X4 V; Y) y$ u8 N<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>% W$ D/ \: H7 b, n$ R
<ul>
2 _; e" b# e" J4 I6 H% x. C<li>与二级缓存配合使用进一步提高查询效率</li>
& j' E  P/ a7 d* [0 m</ul>% L0 J0 [/ O+ Q; F. z* h1 j7 h9 r
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p># q( F0 y( Y1 |5 o
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
9 B3 ]! a. l$ s0 T7 p$ d& x* c3 r& f
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-10-31 04:29 , Processed in 0.198750 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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