飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8034

主题

8122

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

! @; G) ?  Z6 g) r<h3 id="一序言">一、序言</h3>
9 k! W: h/ x9 R5 t4 x# S<h4 id="一背景内容">(一)背景内容</h4>( Q7 A( q# J3 Q3 |% G$ T
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
3 q, x' ~) P/ T9 }8 E3 T<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
2 v7 e7 w. F  f, O* @$ K<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
9 A! }! S7 U  ^# S<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
& g7 T/ _. F  Z8 z6 l4 P<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
8 \9 |; }' e6 @# u$ V<h4 id="二场景说明">(二)场景说明</h4>
0 s5 W+ a+ X9 E0 |+ S* r<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>7 w. c  z1 g* C7 E
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
  N, m  h% {/ ~5 k<h4 id="三前期准备">(三)前期准备</h4>0 [! d  G4 r4 y% M2 R$ M/ f
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>7 f) h# ~8 A( V& N. j3 V  b
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >4 A, b  V& }" Z0 D5 o
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
# y7 P7 _3 ^) U6 k<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>( l9 q8 R& E& u$ P
<h3 id="二一对一查询">二、一对一查询</h3>5 i( v) V1 S& ^, P  s' E9 a
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
8 @/ j5 I# f% j6 y* O$ v8 [5 ^<h4 id="一查询单条记录">(一)查询单条记录</h4>
! K/ u- p+ A9 l/ [# m<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
( D4 O/ ^  C; F: L<h5 id="1示例代码">1、示例代码</h5>
& U/ y/ C3 ^4 h$ Q<pre><code class="language-java">/**
$ P6 o1 A1 ]2 M+ D" i6 i * 查询单个学生信息(一个学生对应一个部门); k9 Q& |) r# F5 K# y/ C
*/
/ N0 W6 b4 Y! `, ^0 |* u6 h$ Ppublic UserVo getOneUser(Integer userId) {2 I" B- `2 \& Z( B/ h- s$ V
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
" [( ~4 z) N7 l+ [- n3 h; x        .eq(User::getUserId, userId);
/ r( ]6 T% W) c& a* A+ y    // 先查询用户信息
+ j$ m/ M, \4 P/ G5 K; E    User user = userMapper.selectOne(wrapper);* I) }- `! T  u+ a9 i
    // 转化为Vo
6 I* _" k" f( S7 _" B. [1 j    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);& x# L- S( ~) X$ i- V2 k, }
    // 从其它表查询信息再封装到Vo
, K+ I# ^  `6 Z4 j0 |    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);" A& R' n* D: q  Y. Y% D6 w$ G  U  U
    return userVo;9 {9 W# O( r6 x: e( X2 T
}. X  o9 `3 s% t  E" U
</code></pre>
7 C5 t& }2 i7 q; J; `<p>附属表信息补充</p>; X% a+ |' o3 X: k8 C
<pre><code class="language-java">/**
0 |! \' j4 x& V1 m: R1 Y& g" A * 补充部门名称信息) x0 |# F1 N4 s+ l, Q. h
*/6 s0 m! f$ b0 ~* K1 t
private void addDetpNameInfo(UserVo userVo) {
& @5 Q. h: H. W1 J# v) D5 N% I# t    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)2 E: _- T5 S6 D
        .eq(Dept::getDeptId, userVo.getDeptId());
  D$ @9 f' F. U3 X6 B; O. ~. A    Dept dept = deptMapper.selectOne(wrapper);3 w2 }! b( w. g( \. r" z7 S( t
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
, f' U4 L9 J/ o' D}
7 p+ S- O/ ~6 H0 Q</code></pre># ^0 t) S' A  S9 M8 ~' [
<h5 id="2理论分析">2、理论分析</h5>
1 {) C( q: k" u: l" X1 {( h<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
! a7 R) {, |* f" \, q. U6 e* z<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
; E9 e' r2 G$ f& s2 {' I8 H<h4 id="二查询多条记录">(二)查询多条记录</h4>2 u3 ?; w% y) q- `/ `; j
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
3 F( i/ R+ D2 S9 @<h5 id="1示例代码-1">1、示例代码</h5>  F. R  a$ }* P3 ~
<pre><code class="language-java">/**1 U6 b$ O' D% J: R2 b$ }
* 批量查询学生信息(一个学生对应一个部门)
' c( F8 E# {" u! b' k */6 v0 _6 h& t3 i$ a
public List&lt;UserVo&gt; getUserByList() {
0 o+ }  S0 f3 }) p# M4 q- T    // 先查询用户信息(表现形式为列表)# k. A! `5 T0 `+ h% C+ r+ U6 P
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());0 S$ N; T% _5 r$ l9 T( P
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());% E# u( P7 J8 l
    // 此步骤可以有多个
' W& L6 k6 B: n. S& u+ \$ }    addDeptNameInfo(userVos);+ m! v9 k& X$ x5 ~. d% N
    return userVos;- a! D* m* n/ V% _
}) j* s4 w# ^2 q7 f/ k5 f
</code></pre>
4 }% ^: p3 @/ z" M, l! M. J9 d<p>附属信息补充</p>3 y" W" h- Z# _+ J) z, @( r' P( U
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {
! x- ^# o9 a4 w! X/ e    // 提取用户userId,方便批量查询$ u/ H. R  @" T7 m% j
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());& I0 \$ V1 s, ]8 H8 A
    // 根据deptId查询deptName(查询前,先做非空判断)
4 ]( w# E6 _; l# Q9 V( u    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));: g3 j. m" E* ^) W" S* d
    // 构造映射关系,方便匹配deptId与deptName5 R2 B/ F! C! D" R8 b
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));( O) C+ f5 y5 V0 r( O
    // 封装Vo,并添加到集合中(关键内容)! k9 N8 k0 E# D& _8 F2 @
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));- P& @$ b: M6 F* o6 p; J! h
}
  r, s9 |" k- G5 _, U</code></pre>8 s: o7 c! N! ?& R$ W! \
<h5 id="2理论分析-1">2、理论分析</h5>8 x+ E) r4 B2 |# L. W
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>' k) P( i9 a8 ?. f, v3 I1 @# y1 v
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>0 H( v' k5 U+ i/ ~
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>! z: q. P( M" z  Y" q
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>( g0 ^1 j: k. e; F
<h5 id="1示例代码-2">1、示例代码</h5>
  y2 q. @8 z( T3 ^! l<pre><code class="language-java">/**
8 R+ `0 q6 `! D+ v+ O8 i * 分页查询学生信息(一个学生对应一个部门)
$ w% c5 l4 L$ |% W */
2 U4 c$ d9 i% c" b% Dpublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
% K  s3 a% |# N) w; k; M    // 先查询用户信息5 _" Y1 A! L$ N  u$ d0 v( U
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
5 Y& p# o; L* O    // 初始化Vo
8 G9 w2 ~1 z9 J' }$ p+ p    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
. o: T4 T2 |6 f+ ?    if (userVoPage.getRecords().size() &gt; 0) {
) s. _& H+ p4 C3 S9 L        addDeptNameInfo(userVoPage);
: ^( b" g9 S# P- l' ]    }% D, A( x! L5 s$ Q
    return userVoPage;
% _  a: @5 u& e3 t1 s6 k}
  g2 P" n. i/ M  K- a2 o</code></pre>
8 F5 ]7 k% M  h5 _# u6 N  o<p>查询补充信息</p>6 D( a, u, {% T8 ~
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
  U$ b- A- S& N9 L2 }" k* a    // 提取用户userId,方便批量查询' o) _8 S; i: a5 f# y
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
; s7 h( c5 y  Q+ ~; g$ R, T7 q( [    // 根据deptId查询deptName
& \- I8 n0 ~2 `$ ~    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));( ~0 c2 k0 Z. ]# K0 f; ^- E6 K( \2 Q1 N) f
    // 构造映射关系,方便匹配deptId与deptName
- _/ q( o% Y/ N    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
/ \5 F7 o4 T- X; D: w& V4 p/ m    // 将查询补充的信息添加到Vo中' z' l5 W1 E  b$ Q' W
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));( B  I$ X3 c2 g
}
" @" @' ^/ J- J' c, ^; e, p; Z</code></pre>
  o& T" W3 X( x3 G# m<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>  I, M2 d; J+ D- e: N* [8 r
<h5 id="2理论分析-2">2、理论分析</h5>" O  v0 _8 e7 ?2 k$ |
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
4 B4 @% v7 K, y2 C4 n8 W5 y7 l+ X<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
4 x( D3 {' @: J<h3 id="三一对多查询">三、一对多查询</h3>
4 j/ J+ J; g7 {6 f( i4 E6 i<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>  x8 ?) I% N# i5 ]
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>/ y4 o8 q0 `& p% E. L; Y' K
<h5 id="1示例代码-3">1、示例代码</h5>6 Y$ p) D" e6 S: W6 Y
<pre><code class="language-java">/**
/ W3 b4 i( r+ z * 查询单个部门(其中一个部门有多个用户)
6 S6 \9 k% g! z9 [4 y) l+ [5 Z */
; c) y: ]* [/ @( _: Vpublic DeptVo getOneDept(Integer deptId) {7 y" [& Z4 n1 l2 S. z- i
    // 查询部门基础信息/ d3 E! z0 e* T) K1 U% r
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);1 A' U) F" q" x# A
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);) p9 r0 y1 i8 Z3 l# `9 ?
    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);8 ^6 Q7 I  ~0 O7 y
    return deptVo;
3 g7 H  L- S: U1 b0 N' o( `( D1 B% `}
4 l" ], i8 l& ^- A6 o$ W" y</code></pre>0 P3 B0 y" Q" l  U0 e+ S+ f. h
<p>补充附加信息</p>  d8 O+ _$ `1 M1 |, H; y- |
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {+ h# S- k$ q: i
    // 根据部门deptId查询学生列表+ y; T' r, m1 i1 J1 n! L
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
* f9 v, p1 @7 i6 v  ~$ B    List&lt;User&gt; users = userMapper.selectList(wrapper);9 T" ~, k! h* {# T
    deptVo.setUsers(users);9 ~5 m) ~* e" X1 H7 f- m& A
}
: A# u3 \0 J: W- C6 I% v8 H) ^( {1 h</code></pre>0 a0 N5 d& A3 f0 m
<h5 id="2理论分析-3">2、理论分析</h5>
) L( L: I  w7 |% F<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
5 i- x' ^0 H1 f- ~" }8 r( B<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>2 o: f3 R3 k. `# s% G
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>1 y; {$ y5 o) M8 h  J
<h5 id="1示例代码-4">1、示例代码</h5>7 y  C1 q: b0 f8 X- C8 [
<pre><code class="language-java">/**. c' J9 Z# O4 w! V
* 查询多个部门(其中一个部门有多个用户)/ L3 s2 Q: {( Y6 u* \& I) ]4 E
*/  Y. o# y7 {8 L- t" L" G
public List&lt;DeptVo&gt; getDeptByList() {% Z( U2 I3 D) x3 m
    // 按条件查询部门信息
9 k2 u2 n! ~4 ~% D) ^% b$ D    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
$ _* B4 u; w# J# T    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
8 P: x, ^. g! x" z5 B' I    if (deptVos.size() &gt; 0) {
5 s' d7 N1 g9 P# N( X  j        addUserInfo(deptVos);% E! s) X5 C- J) _1 K& r
    }
6 m7 ]! v0 q- n' W  F    return deptVos;
& K. F- c" p6 _$ _4 J- f}  k7 P' }: ]: ?; u' ^
</code></pre>
  D! V) a# w8 k% ]6 ?<p>补充附加信息</p>: }$ }& E0 s' Z( ^6 c9 `
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {; `0 I$ B6 C8 _
    // 准备deptId方便批量查询用户信息; x# s. B3 r* F' c
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());/ J2 j& G4 {# L. w+ Z: z: T
    // 用批量deptId查询用户信息& t( O* F( x( Y7 L; F) ?
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));' Y& K4 |* D, s4 K1 j
    // 重点:将用户按照deptId分组
$ w% j- V6 L2 Z. u  E3 r, B    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));# f+ h6 C, ~* L& F, g
    // 合并结果,构造Vo,添加集合列表' X. G/ j9 ~, y/ V8 D" Y
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));% @; i0 m/ m/ a" E6 }0 D6 k  F
}+ g9 l$ S* |& I* o$ Y  r& f
</code></pre>
7 }* p2 ^- F3 A( g# X/ x<h5 id="2理论分析-4">2、理论分析</h5>
, S  t) A. Y) R5 L7 R( ^, U: M3 P! h( J<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>1 f+ [& K* n3 _4 C# b8 Q8 Y9 y( y# x
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
$ V+ L; J1 T# u: O<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
1 ]1 [8 q2 \/ _& g<h5 id="1示例代码-5">1、示例代码</h5>
4 {) A" }8 K$ p! r' [! ^<pre><code class="language-java">/**4 L4 }+ j5 {( g" r
* 分页查询部门信息(其中一个部门有多个用户)- ?) j6 P5 t" V1 o5 n; z! Q" F2 i9 V
*/, H& ?% y4 _% f5 Q' {
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {- \7 o* {# X: L1 h
    // 按条件查询部门信息
: o& K' V0 S9 h: _) k    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());% Y3 G6 j0 c6 ?& }. w4 e1 Z6 d
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
+ V4 w& X( t" M4 |  k0 y    if (deptVoPage.getRecords().size() &gt; 0) {
- j1 M' Q( y% g+ `        addUserInfo(deptVoPage);# j& Q  ~) |6 }% Z4 o! r
    }- f3 Q1 h1 d8 y
    return deptVoPage;4 V. U1 [6 ^- B8 G8 n) }0 e
}
( D4 z" @* m2 A' b. g$ U0 w+ \" V  b( X</code></pre>) T/ L: b4 L6 W, s6 h
<p>查询补充信息</p>
/ l0 N8 {/ j4 g4 s<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {4 z& T3 w4 |' k& x4 j
    // 准备deptId方便批量查询用户信息7 y" l& U/ X6 E' U& x6 q/ V7 Q. [
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
* L; v& ^; M6 M0 E( m) ]    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
# @" s9 Q( A. o' K    // 用批量deptId查询用户信息: |+ W: P2 u) ~( f; `) {
    List&lt;User&gt; users = userMapper.selectList(wrapper);# A' k- o; @4 n
    // 重点:将用户按照deptId分组
2 M- D& P: X1 g8 v  j    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));' S, e" ?7 Z% l" p( g
    // 合并结果,构造Vo,添加集合列表
0 w5 Q9 b( I1 k8 G( n    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
0 y# m+ H: g6 G# z7 k}
3 q% C3 I" _3 o9 n# O$ J# ~</code></pre>
9 z7 H- }$ h# ~, z) r6 i9 i<h5 id="2理论分析-5">2、理论分析</h5>
0 S4 z- h; o' @0 F) u8 m<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
* Y+ W! ^( K1 E0 T2 e  t<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
# i+ k$ `, i+ M. R( J: v; h<h3 id="四多对多查询">四、多对多查询</h3>
3 R8 q* L% Q! b; L<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
& \& N$ F, u" ]<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
! j) L( y% _5 j; e/ _* Z. g+ H& ?<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>& ?: O0 z( }4 [" x: z
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
& u- B  o- v6 w  I( t* ]  k4 c<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
% T8 c1 X/ k- J5 c* c2 H7 M<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>2 I1 ]% t9 O& A+ B1 n0 a1 i
<h5 id="1示例代码-6">1、示例代码</h5>+ C4 O3 ^6 p5 P* i8 z: E9 V
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
9 l! J5 D/ x5 r    // 通过主键查询学生信息- J$ @0 [" c* h* q4 T  X0 w: p! _- R
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);9 ]' ?+ m; c* V& a$ b- R
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);; }0 R! u$ O$ f% Z' [
    // 查询匹配关系: T* H6 |, f/ J& b) @
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
2 ~9 s8 k& P/ E- H% _8 e8 v    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());, t0 u2 F3 i& K( x
    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
( ~, W* `3 Y8 |. `        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));9 c( Z  g! Q4 U8 }7 p. I
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);5 C1 i, {: ~8 H8 O$ k' Q( d
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);- g1 r  A4 X; z3 D# q' L
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));6 k* [, |2 r1 K- z- f. P8 s
        studentVo.setSubList(subBoList);
$ F6 m& e- M/ l: O    }/ S  H, X9 l1 B* r) X
    return studentVo;
( L! j3 e8 L& p- x1 f2 ^}: D! N- I: ~( l8 t4 G% c1 L
</code></pre>
( N6 ^  c6 X. |' d* g' j<h5 id="2理论分析-6">2、理论分析</h5>/ E* S4 n& z. Y. \4 C
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
3 i' z4 n* W# n% k/ }9 N; h6 M<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
9 q. ?; u/ E! c: K0 B<h5 id="1示例代码-7">1、示例代码</h5>
8 l' I: u4 ?" f8 I! [8 l<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {! w6 C  ?. g- u" P. W- n
    // 通过主键查询学生信息
0 d0 R; v- y* E' n$ S' \    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);8 ?6 R) _% [* `. D; ]) t
    // 批量查询学生ID  F+ ~% x3 B0 Z% c
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
$ V3 [' E4 g/ @, @; g1 Q    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
" b$ U% X0 p/ m, B    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);' Y% E# P1 S# S0 e
    // 批量查询课程ID
0 h5 a+ |3 I% N$ O    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());' I! y4 m8 H8 h5 f4 \
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
( V; i9 V) ?: j& c9 A+ S* g        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
7 v; W; ?2 O( {/ j1 ~+ S        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));+ x( j! }7 y/ [" P, g( D7 W* D
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);* l# m" M6 y; e& u
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
  \1 K! T# c! V+ M4 ?        for (StudentVo studentVo : studentVoList) {& N  T$ m. F9 A3 I/ A. b
            // 获取课程列表
1 x) ]3 o$ @; S' o$ O2 L; F            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));* h" o0 m  _; ^. X2 R2 W. a( V. S
            // 填充分数( _+ a- i& H' J/ V
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
$ @  w; C% ~7 O" B, e            studentVo.setSubList(list);
( Z( |2 h4 B' p( p3 e        }
1 ?+ A7 G3 {' u    }
; k  V$ l& j6 ]. Z  ]    return studentVoList;
; ?7 \/ f+ {& {6 u/ c0 |! a}
, u  O: s- V9 [, a3 P* N! N, ?& N7 ?</code></pre>$ j) k# A$ t, Y- L$ T
<h5 id="2理论分析-7">2、理论分析</h5>6 a  K" t, f( j' J' b; X7 ]
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
. Q4 T1 Q: ?& H$ C" d<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
) }1 a, i6 \" m8 I2 D: V. D<h5 id="1示例代码-8">1、示例代码</h5>* W* K' r" E( F- d
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {) \8 q& G' S7 o
    // 通过主键查询学生信息2 y- ]& K) i3 T/ W
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
  p5 [! h/ D. ^    // 批量查询学生ID
: M$ N8 M8 c' [4 O6 j* p    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());3 Q5 T) N; G+ ]) i5 W4 _& k; t0 W5 R) l
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
) ]. c/ h  ^4 A7 @' L' I1 g2 e* _: s: i    // 通过学生ID查询课程分数
: ~& Z9 I1 o! H/ ~+ M$ K4 q    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);& ]. f* j; S" S/ w6 Q
    // 批量查询课程ID5 L! \8 q) c' h8 k% I1 z% H6 z
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());# G5 o4 R+ s4 m- D0 M; y/ D. ?
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {0 X2 q- _. F8 u5 ^6 S: p- [1 a& d
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
' g& h* g2 @3 W- S: N        // 学生ID查询课程ID组+ d7 z: |$ H2 ?- i+ H
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));" |$ o2 f) h  T+ a1 V7 E& X5 i

& v3 y9 ]% R% J/ W( a, R        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));% q0 }9 C4 N9 \( k5 g
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);& j) y7 u) g0 Y8 X7 o
        for (StudentVo studentVo : studentVoPage.getRecords()) {
5 y. U( Z/ J" [! S            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
4 D3 X# r& ^/ L. T% B; c# \            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
" ?( p" `. C  @            studentVo.setSubList(list);  t; P/ H3 A2 I) W7 X' ~2 j
        }
$ [9 O3 |6 B8 }4 w, m7 G# X    }
' r, x$ \6 Z, M. m+ h% I+ ?( b9 E    return studentVoPage;) e2 W& l3 ^, y, V$ Z; P
}/ j: w6 u2 `, n, b2 O
</code></pre>! m  \5 D; t% K- W; D4 J
<h5 id="2理论分析-8">2、理论分析</h5>
; r$ f0 Z8 ]7 d3 A( @<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>2 y  i) _0 p; c0 Z  v
<h3 id="五总结与拓展">五、总结与拓展</h3>- C' t3 }& f" p* R
<h4 id="一总结">(一)总结</h4>) Y( H, l5 P0 `6 b4 Z% Q6 Z
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
& }/ K: z5 U; n: M<ul>0 y/ z% Z0 Q& S0 C/ a) c8 d
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>' s. P4 _- u  C( A  K5 p2 b2 b
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>6 F2 A3 i: I$ N2 C: u) f
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>2 E+ |6 j4 l! D, W& f
</ul>4 `3 S" ^4 B& \$ H% B, v
<h4 id="二拓展">(二)拓展</h4>) Q1 c! z. ~4 b: s' T( f& v
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>& n6 a& o: m6 x* {3 |
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>  j7 g) y: D& v/ \: M: K) d/ S
<ul>
7 d$ J8 j4 k, }<li>当数据量较大时,仍然具有稳定的查询效率</li>
3 w( L: i5 t9 ^0 t% y/ ?/ c</ul>6 U% O5 T; @, k* @5 e
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>/ j9 N4 h" U+ Z1 Q! ]
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>- U2 M8 a% q. `; {: o+ G
<ul>, a' X6 f$ ?6 M7 w
<li>与二级缓存配合使用进一步提高查询效率</li>8 m* v/ }7 b: w; T
</ul># F" s/ o$ y& H; b4 {; a7 B
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>; U, k% Q, Y3 \
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>! R' V0 w) x) X4 C

  V% G+ Z8 s9 |& V- g
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-5 01:29 , Processed in 0.073495 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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