飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8131

主题

8219

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-27 02:23 , Processed in 0.066232 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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