飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8087

主题

8175

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-17 20:20 , Processed in 0.064700 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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