飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8042

主题

8130

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-8 16:15 , Processed in 0.075545 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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