飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8019

主题

8107

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-2 05:30 , Processed in 0.083210 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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