飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7673

主题

7761

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

( |9 w& Y( s& |+ O* R
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-10-26 23:43 , Processed in 0.103154 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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