飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

6738

主题

6826

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

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

8 o8 I7 A7 [. c) J
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-6-15 15:58 , Processed in 0.421011 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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