飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8058

主题

8146

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

5 p" R5 P" [) t<h3 id="一序言">一、序言</h3>0 D6 r3 E) @' H/ G- I( ]
<h4 id="一背景内容">(一)背景内容</h4>' S; k- A8 N" I. J: P7 E
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>3 W; L* y/ g+ Q& {% M3 A: Z% L9 [1 |
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
4 W& J7 z0 M3 I# t8 W<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>' `/ e, W3 B( k8 q- O9 N3 O& G8 c
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
0 g. N; j/ G2 F& X( |! n2 Z& X! `<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >( V/ l, z' g+ V4 Q4 \
<h4 id="二场景说明">(二)场景说明</h4>
2 T* ?) x) U5 w% l/ L* ?<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
5 t2 l: r$ H: p* L) K  |<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
7 g' ]$ S3 d" |- Z# w$ f/ e<h4 id="三前期准备">(三)前期准备</h4>
* D7 ?* T  M2 ~9 i<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>2 G- n$ e  R3 w3 e/ Y" s9 ?
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >8 \& i3 D; |9 n  Y
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>& k8 N, U1 H2 L8 F6 J! u/ }
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
9 _9 f- R3 W6 N5 U( }6 C5 Z4 s<h3 id="二一对一查询">二、一对一查询</h3>
1 I' s' O- I+ m) g8 n6 V" P<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>4 J4 M) P, j( [
<h4 id="一查询单条记录">(一)查询单条记录</h4>
/ J' s6 n! O/ Q' ^* _( P<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
, u7 A# a3 P0 v) ?* s<h5 id="1示例代码">1、示例代码</h5>1 X/ O. ^. I* r+ X/ |
<pre><code class="language-java">/**
  e  s/ l  j: _5 Z * 查询单个学生信息(一个学生对应一个部门)% \3 |/ n8 H. V; [' [5 }& g4 L" v
*/. v' p% a3 M8 r) A+ U" p5 `) P- P
public UserVo getOneUser(Integer userId) {1 R- J3 q( p6 x) I* O
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
! q) j. l  o) O5 {9 w  @) T        .eq(User::getUserId, userId);
2 v$ @; h$ S. K/ E5 }; I7 k' O    // 先查询用户信息6 ?/ X" s/ n& k4 U7 B
    User user = userMapper.selectOne(wrapper);, f* b4 j9 q% ^" h! \& \
    // 转化为Vo" n# A6 y, Y  _) D. }
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
3 p* O. h& o1 j0 r, Y0 P    // 从其它表查询信息再封装到Vo/ g1 M7 I* N; C$ h9 F
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);6 g3 z3 n' t1 Z# `5 a3 B0 Q6 S
    return userVo;
: ~  z" c, t) [$ e& d}! N$ M5 s+ g) u5 U& C& i
</code></pre>2 r$ W7 b% ]5 W. d* T+ L( L
<p>附属表信息补充</p>
, Y2 r2 W7 r4 r/ K+ a<pre><code class="language-java">/**1 Q  X( B1 D4 v! t  C
* 补充部门名称信息  Z* z7 ]- [5 b
*/
* }" R/ ^) b8 `& U* V. s  T- \private void addDetpNameInfo(UserVo userVo) {
# _1 O2 {) ~0 J  F) D6 K) M    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)% ?8 j9 v; @4 {4 R! q) u1 M  ?
        .eq(Dept::getDeptId, userVo.getDeptId());  B* w7 E; g7 B* a; F4 v
    Dept dept = deptMapper.selectOne(wrapper);9 [$ P3 U6 r, h1 }" \
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
/ z+ ?7 E7 u2 o2 _5 F- u/ L' H}" q) O2 H8 a8 r4 c( I2 s
</code></pre>
- t7 Y6 h) D: Y7 x' e<h5 id="2理论分析">2、理论分析</h5>6 ]' z- X# ]/ S- _* a" `  M
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
: q3 v' g. Z  H0 E3 C4 w<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>2 p6 o. r9 ]0 h; }. x1 i3 b" e
<h4 id="二查询多条记录">(二)查询多条记录</h4>6 h) g3 C1 M- @- Z+ y6 G
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>' W; s- U! u" x) n
<h5 id="1示例代码-1">1、示例代码</h5>
1 X, f# Y  ^* G8 v% l0 E2 t1 F# P<pre><code class="language-java">/**
* L( O/ l$ w7 Q& H+ f  M0 W * 批量查询学生信息(一个学生对应一个部门)0 I* `7 K0 Z8 r. W
*/
" c; D* k( m7 J" u3 }7 @& xpublic List&lt;UserVo&gt; getUserByList() {' `" w5 e3 v7 R# [* j1 ^
    // 先查询用户信息(表现形式为列表)
( Y3 `* A) x; x; T9 q' N    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
% w% J4 @! v( {4 V6 E    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());, r6 o$ Q; F& q+ [  r$ E1 E4 }
    // 此步骤可以有多个
* D: P  l/ s/ a    addDeptNameInfo(userVos);
9 M+ E$ M# u4 G8 d. Z& s    return userVos;
( D" Q; ~, b2 o' v3 X9 N1 S. f}
% V* F( Q. V" z8 v- F</code></pre>
( y! z* \5 j9 R' @$ H# j<p>附属信息补充</p>
2 m* A+ ?5 o% Q1 i. U* z. A<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {) R: y- H% _9 k' I/ L# w
    // 提取用户userId,方便批量查询
; O4 {4 v6 b/ `6 r2 m- U1 M# J    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());8 d1 z: d: v( q  T) f- l! d
    // 根据deptId查询deptName(查询前,先做非空判断); b4 d; R. Q* ]# d% I- ?
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));0 i" l; X* i/ I( O. a" T
    // 构造映射关系,方便匹配deptId与deptName
/ h6 S2 }! F- u; }! V8 A1 C    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));3 q/ A! K2 O8 x* S7 u# c- S
    // 封装Vo,并添加到集合中(关键内容)
1 X* U% A6 @% j& n# ~2 s7 v0 D    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));2 X5 ], @: Z- ]5 t+ \* c  Q
}
4 |1 n5 H( o* `7 U( R% g$ {</code></pre>
: \( z# e; |8 c6 Q/ X, x4 i% a<h5 id="2理论分析-1">2、理论分析</h5>
6 U& m0 x: }( B# t+ _* M<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
, S3 X1 i5 L4 \. u' P5 I3 r. M<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>: q# d! U( K5 i# O: B; [8 q
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
. @- r6 @/ g4 R) I. `/ z<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
( a0 \$ L( ^. v0 Q<h5 id="1示例代码-2">1、示例代码</h5>0 a* s! n- m, B% B
<pre><code class="language-java">/**+ Q+ }- T$ |* Q
* 分页查询学生信息(一个学生对应一个部门)
2 {5 A2 V' U, R) ]' t" p9 a" D */" R1 J5 i& V: P% j
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
9 e! B! [7 F) I& D    // 先查询用户信息
! n4 I& P; Q) _( f! D3 o    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
4 v- \. P$ s; W8 @6 v4 P    // 初始化Vo! X: V% j! _) [. A2 D  v
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);- l$ V1 |7 i  M+ o/ D8 L
    if (userVoPage.getRecords().size() &gt; 0) {. h: m/ V# p; i4 c5 ]
        addDeptNameInfo(userVoPage);
3 N8 |1 B, z9 }" X3 p, U6 J! m0 W: w    }, c* P) F+ U" A
    return userVoPage;6 }/ E. E  U( u+ s. ]5 u
}
% l/ d, x' R3 e</code></pre>$ f1 @1 q8 K) \8 |7 Y9 m2 U% H
<p>查询补充信息</p>0 v9 f* {/ X7 T: ^1 E& ~' k
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
( {+ N- ^0 `- c- U    // 提取用户userId,方便批量查询
% o/ m5 `' ~0 N. i3 r. Y    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
* r4 Z$ Z+ P3 Z. G9 H) k0 C. a    // 根据deptId查询deptName+ F3 o9 V; i/ ?* f: Q
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));+ N  [9 r3 {: n3 i
    // 构造映射关系,方便匹配deptId与deptName2 _- I, e/ V* z+ L, l5 V( Q+ L
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));$ V: I+ S0 Q  j8 i% j
    // 将查询补充的信息添加到Vo中
3 C6 {( g& R$ Y% [+ S# g5 o) N    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
5 D, w2 G, U  T}
& f5 D1 d' c$ U) H0 D</code></pre>
3 Y" s4 H: _" t% L: Y- p: B<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
4 P/ z& }0 K( e<h5 id="2理论分析-2">2、理论分析</h5>8 E- `& X' q, Q& P
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>7 S3 G* [+ D$ \" V
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
) u0 B9 R9 x- m' F- h: J6 {; Y<h3 id="三一对多查询">三、一对多查询</h3>8 H' E. C' z/ \( j: y  |( L
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p># C3 @) E& }9 V/ {6 v, J- C( F: h% q
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>8 d- Y7 \* c/ a" x) A& l
<h5 id="1示例代码-3">1、示例代码</h5>
1 o  D6 d: I) b' ^<pre><code class="language-java">/**
0 x3 M# a; b3 M( Z' O" [" b * 查询单个部门(其中一个部门有多个用户)  C; h( O3 j" r/ a- E
*/5 y  V- O/ r' t, Q9 x* O8 @; d
public DeptVo getOneDept(Integer deptId) {% y. [( F1 ]( q( _; K5 S) V' Q
    // 查询部门基础信息
7 G, z$ c" G' Y! S  x( {: a. F    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);; V1 J' H) J- Y
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);! J6 {* ~/ Z  l8 n- }1 y
    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
, Y8 e$ p, Z) R! ^0 a' |7 Q* w. M    return deptVo;
( R% n2 {% _) d}5 v! v* {' t% n( Z
</code></pre>
  F$ T/ m( O4 S$ j2 I7 t3 P<p>补充附加信息</p>8 B8 s8 z% J) w2 R
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {% k% I2 n8 o7 Z, I" j7 ~; e8 ^
    // 根据部门deptId查询学生列表& Z- G. ]9 J, d& B# ^
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());. w# r2 G3 Y  `
    List&lt;User&gt; users = userMapper.selectList(wrapper);7 S8 ]2 r( U  R% J
    deptVo.setUsers(users);
% s, X/ U9 |2 R9 l}
4 I- R2 {: ~% \; T</code></pre>! w1 D% {! W6 B. J
<h5 id="2理论分析-3">2、理论分析</h5>8 B6 A9 u/ i7 h# N1 ^
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
7 ~! S$ a$ e( a. A) D$ ~<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
' V  T+ p# m: W6 W<h4 id="二查询多条记录-1">(二)查询多条记录</h4>) w1 B% C9 \! C8 w. H% `1 S: W. o
<h5 id="1示例代码-4">1、示例代码</h5>2 s5 c7 W: [) n) R  n  m" u
<pre><code class="language-java">/**
% s9 ]% i  L: B0 S4 g * 查询多个部门(其中一个部门有多个用户)1 j1 h- r+ J# m) ~
*/' p7 t2 m" u4 l. w
public List&lt;DeptVo&gt; getDeptByList() {1 l* ]) J+ d) C4 i" B
    // 按条件查询部门信息
; ^! n3 G% N8 K    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
! R8 l; X% t* B8 f0 K$ @- v$ d    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());. k: T0 F2 W8 i  x
    if (deptVos.size() &gt; 0) {
8 ?- O9 |5 x2 A- h        addUserInfo(deptVos);
. b$ l: N; A; |! T9 K    }2 U8 P7 l% H% o. {
    return deptVos;, p! j% f9 b8 S1 S
}
4 ^1 A) d% b4 x' V; w</code></pre>
' |4 ?# Y6 B4 g7 }! N0 D<p>补充附加信息</p>
& k8 ]" V) F+ P% U/ K  @<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
: Y6 ?4 n8 [7 o, V% c    // 准备deptId方便批量查询用户信息
4 y$ ]5 b+ J0 B# N5 ]  E    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
: T$ K7 G3 _  q% z/ `3 y' t4 ~    // 用批量deptId查询用户信息/ N% E5 Z2 H% l, E9 U, W: g$ L
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));* v5 P$ J. v% M( Y
    // 重点:将用户按照deptId分组& y- Y  \; s5 ?* D
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));' z& l( g4 T4 J0 c
    // 合并结果,构造Vo,添加集合列表
4 X0 n0 _% \" l( T& z- y0 q6 F% p; u5 x    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
! w0 e" p) \) ^& [( X}
7 b* U4 v/ f8 p% R</code></pre>
$ i6 t: p, Y( k" s<h5 id="2理论分析-4">2、理论分析</h5>
" G" I2 ^; g0 J7 G4 t/ m8 w5 ~<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
! L8 _! J7 f3 m. X<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
- V( {7 h- @# r( u% `<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>' U1 B: l/ }# S- u7 N$ O5 W6 ?" J5 k
<h5 id="1示例代码-5">1、示例代码</h5>4 n) F2 U# F6 H6 y; m
<pre><code class="language-java">/**0 s8 k' a, C. P6 C7 B+ H' P! u" n
* 分页查询部门信息(其中一个部门有多个用户)
: ]" y; A# X" q8 D4 i */# i. Z* M8 `! V. y9 |0 v
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
) _* W6 G- K% e  W: p5 X6 [) A+ W( p    // 按条件查询部门信息
3 v2 e6 q  a. C' X5 A    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());. g/ T; r3 u' g; k8 i
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
% E0 a, w( @) [0 W6 V+ b    if (deptVoPage.getRecords().size() &gt; 0) {. i+ l5 \9 e- \6 ~/ `
        addUserInfo(deptVoPage);+ F9 N1 J1 _( D" z. J4 \0 z# ~: ~  q
    }
( F, |. V0 @/ ]2 Q8 }    return deptVoPage;
8 A3 o. D4 P6 e' O5 ^; Z}. Y% h4 R$ s" b% L
</code></pre>
5 r8 }( a0 b' H: ?" H# l! g5 ?" J% V8 n<p>查询补充信息</p>
8 {# N& U& V* a, s4 e5 B; I3 J  N5 h& X<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
# Z3 f& v/ t$ F1 F7 A# X2 z    // 准备deptId方便批量查询用户信息
& b! S+ u2 b/ r7 d+ |! d9 @    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
% r& G6 [3 M  t6 [4 C4 u    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);3 B; ~" J1 ]4 H- T
    // 用批量deptId查询用户信息
' f& s! G! ~2 ^: ^# D4 @0 n* \    List&lt;User&gt; users = userMapper.selectList(wrapper);) w$ c5 @$ H, [
    // 重点:将用户按照deptId分组+ G; ^/ O/ A3 l0 y8 U; _( U
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
6 [- b- V* F( L; b3 U" i    // 合并结果,构造Vo,添加集合列表% L2 c4 D$ Y9 W, }
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
+ k1 R8 ^2 c: g, D% X9 g% B}9 @# V5 A# y9 m5 r
</code></pre>4 ^9 _  @3 \& K+ \3 F" D
<h5 id="2理论分析-5">2、理论分析</h5>
9 q9 S$ R8 {8 C6 f/ N5 g<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>4 A' {2 q3 G7 x: R, B" h( k
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
' b9 M) E7 W/ {/ W9 S4 a$ a<h3 id="四多对多查询">四、多对多查询</h3>
; g! N+ N9 k) V0 o' k( z<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
( A$ ~9 c, @) w) m$ _<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>. y3 S7 ^' K, o; A
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
4 e. F2 p7 U# f" e4 l<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
" Y+ w% R, Q) s- e* f! O# Z<h4 id="一查询单条记录-2">(一)查询单条记录</h4>3 c5 {) o% c' M/ l' O
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>3 [( Q& |! G& G/ J+ Q. W2 |" y# L
<h5 id="1示例代码-6">1、示例代码</h5>
% ]! S/ R" Z3 ]$ [<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {7 A! t: D4 d0 u: @
    // 通过主键查询学生信息
% j1 U! w1 `4 A" d1 M+ U+ k    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
8 I; Y$ h/ w% _% U    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
& E4 N7 d+ S, C    // 查询匹配关系0 P& f2 D! C+ N7 p# c+ x2 v
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
4 X. x2 y  o5 ?  a6 h2 j& r    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
  j- v& h0 U  j! P% W6 F    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
- _1 Z# e5 h$ {) E. S        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));6 F1 E: l0 [& H/ ~+ \
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
' j( [% Z9 G; q7 Y, R# y, N# C5 s$ V9 ?        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
( j. T- X4 w5 p5 o1 x        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
5 u4 G3 C5 _  e% V        studentVo.setSubList(subBoList);
; F7 Y* Y# R: @    }! b& |- X7 c% s) G: Y& x/ M/ d: y# v
    return studentVo;
  k* _+ E4 o& V}
$ I: F' A+ O( y% Z0 Y9 ~</code></pre>3 g! z$ u3 @9 Q
<h5 id="2理论分析-6">2、理论分析</h5>
; E7 A. W  e" ^0 c2 S<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
, j6 |5 J9 z8 H- @8 K<h4 id="二查询多条记录-2">(二)查询多条记录</h4>0 f& u; B- p& W; H3 x9 j
<h5 id="1示例代码-7">1、示例代码</h5>
' Y( t9 u* R1 f4 g<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
" |- r* k( [( ~( T5 p0 p    // 通过主键查询学生信息
6 t3 J8 {0 E6 D  D    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
5 X9 `$ c7 L+ i  x, N: }9 V    // 批量查询学生ID
4 B. n# k1 s9 ]: ^* B4 ?    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
/ @6 U; @# N( h    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);) ~9 g) w9 g8 i9 ]) d! n  X
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
% C0 T7 F& T: i. @$ A    // 批量查询课程ID
" w8 K7 R0 G- B% [$ C    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());+ \9 b1 T# H) [% |5 M
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
9 N8 \' l, E+ o# c9 Y- s        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
* p: F( u" c) V1 }% C8 Y( c5 P        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));) {6 r1 J% }6 I( }" l/ l6 H$ o
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
: X7 E2 m! p4 [5 o' E0 n2 o" Z0 r        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
; Z- {1 e6 U, R9 a        for (StudentVo studentVo : studentVoList) {$ {, Q! s* i' O* c) G
            // 获取课程列表- R' K5 Q: M& k  k" B
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
2 z( k  l( F. y7 F# T/ g$ S* @            // 填充分数( Z3 L$ o- p1 s+ g6 t* a0 b
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));# g- O' k; W$ F" \9 F
            studentVo.setSubList(list);
$ G3 [; I4 S* `        }" [( l. C7 _  B8 R4 @3 M5 G
    }
. v' M5 j7 p5 S' ]7 e' F+ ?    return studentVoList;6 o/ X. b7 n* y/ N$ T& t; Z
}' \2 m' G8 b' Q" N; c5 @8 k8 u
</code></pre>: b8 L5 i9 r( j, u* |" g9 x6 [
<h5 id="2理论分析-7">2、理论分析</h5>
" S  {, y  u% R$ n<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>6 c5 M& O  G% N7 {, c# H
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>+ \/ h  Z6 f# ]$ J: ~
<h5 id="1示例代码-8">1、示例代码</h5>8 s- |+ Z7 Y, w, o0 }/ Y
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {" O" {9 C; |; I4 t" `
    // 通过主键查询学生信息
: o! o4 X6 O$ {1 d# y( \# j) k    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);4 R1 h4 Q; t; Z9 ^. i
    // 批量查询学生ID
  c8 B# H; h4 H- p1 R7 x8 r1 F    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
' L& u" d) S8 t/ L; e    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
  W! H" K8 ]/ w    // 通过学生ID查询课程分数% p- p! C* L$ _" N
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);- _" i6 _, @8 O: @  h% z
    // 批量查询课程ID
+ V. v  H6 Q# Z+ Z# x' c    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());' L3 R0 C- j; O% W( X
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {7 U2 U; E: y/ @
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
: m# E6 X) a% J& \  H# S4 ^! j        // 学生ID查询课程ID组
0 o' R# \5 q) A        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
0 `4 w+ u7 P1 Z) f5 X
/ G5 C. j. f! T  w) v! v, v" m3 s" t        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));; e* `* t" x1 U9 U  t1 k
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);! Y* ?# f- L6 h, {  Z/ O
        for (StudentVo studentVo : studentVoPage.getRecords()) {
$ V7 V- V7 W3 N2 ~) h; l9 U            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
7 B8 Z, [1 s+ n6 d5 M6 X            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
" @3 n  t* L5 P, c+ p            studentVo.setSubList(list);
7 N. D1 R# r! ~/ K: F        }; F7 |  X* `0 x2 @' S- v' ?
    }
) I4 w* L! q* S7 O& B3 B; m    return studentVoPage;& O! X& J' H5 M( @2 _; [
}
2 a, A$ A) d% ~3 K3 m</code></pre>+ @& o* A8 H4 \4 k. i0 W0 C
<h5 id="2理论分析-8">2、理论分析</h5>) D1 y2 }! t3 L9 t; Y0 K$ R
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
" C8 L" p; {9 n* J2 i2 T- ]% C0 X<h3 id="五总结与拓展">五、总结与拓展</h3>: w/ V% W6 D- Q9 P! t. j9 C9 f
<h4 id="一总结">(一)总结</h4>
6 e" T- I3 f+ w# f. \! }" e* S3 O<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>5 I! K% B/ S1 x
<ul>5 T  {9 A4 ]% g8 `/ s7 ~# }" b: u% f  p
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
, v2 v/ _' P6 N) G) j9 b  o<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>3 V& J% I' u7 o. m/ ?+ r% V
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>' V& X2 t& _0 A& C  @8 u- I
</ul>' d* E; ^) ]5 ~  e& s
<h4 id="二拓展">(二)拓展</h4>
0 z% a, E; B  L7 R0 L<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>1 ?4 e  o6 e+ G* O7 t0 r
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>1 u5 r2 Q% I- s- L( ~6 z
<ul>3 [' _3 S( i9 c% S# N0 Q
<li>当数据量较大时,仍然具有稳定的查询效率</li>" v/ h8 J9 k- N7 c& r
</ul>
% v3 e9 X& s% x/ j  ]  ]<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p># D% @3 n+ g1 y+ R
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
, L( m( x9 P$ [( c( a<ul>
0 i: l8 X: W9 V& T7 H  R. W<li>与二级缓存配合使用进一步提高查询效率</li>
7 C) w* }8 O0 |# c8 v- x- a; B& v</ul>
0 W; \( X5 o4 I<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>' B* U, V6 [$ d0 P  u) x3 |/ h
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>/ X9 f3 F0 u, b. j9 l3 K0 @
# C8 |7 L0 y! r! L1 D# p: c
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-13 15:44 , Processed in 0.143465 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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