飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8219

主题

8307

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

- C, x2 V  |- `5 e+ l7 C<h3 id="一序言">一、序言</h3>) Z4 g7 j) U+ V7 n% e: Z( x
<h4 id="一背景内容">(一)背景内容</h4>
- A, E/ X+ p- s5 W6 E<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>/ D: F7 N4 S) ?2 }  r8 h
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>6 x% I' ?* o* }/ b4 O$ w4 F; X+ w
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
9 T% Q3 t( D  t+ t<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>7 O6 P' T, t; n8 u7 l0 c. Q
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
2 D7 e3 `& M5 U3 R<h4 id="二场景说明">(二)场景说明</h4>5 b- G& z, Y; n! A+ m& H, O
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>9 k+ m  u6 N1 i
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
' J' V0 `0 n" I( F1 P<h4 id="三前期准备">(三)前期准备</h4>( f' e) \8 J+ D( W. K+ C
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
4 M8 L& A# d( ^4 X8 R<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >8 l1 V& p( T8 \* B# o
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>1 `, c, v) X* @5 ~6 M, v1 a/ ]
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>5 H6 B( z7 l5 c* m
<h3 id="二一对一查询">二、一对一查询</h3>& t1 K4 d8 I, {( ?& z* H2 ~) ~3 H
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>/ t) L: y2 u; Y, a5 `+ V
<h4 id="一查询单条记录">(一)查询单条记录</h4>) R6 m1 f, c7 o4 ]  y8 _* f, W
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
" P/ n, s/ u  Y* T% ~% ~7 t<h5 id="1示例代码">1、示例代码</h5>$ d! h  l8 q4 d! d; P
<pre><code class="language-java">/**
, J$ t* Z& c3 m" ~4 f$ N5 L' ? * 查询单个学生信息(一个学生对应一个部门)
1 q5 X* x- x! ^1 Z/ w9 G */" H: d8 {- u6 s
public UserVo getOneUser(Integer userId) {
- c0 e5 J) Y; n6 O5 n    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)1 b8 R/ D* G4 }1 e
        .eq(User::getUserId, userId);
6 n3 {- O: a" K( p. m5 w, F" L- [    // 先查询用户信息
) P; M( `# u; u. B, c4 t3 [/ v    User user = userMapper.selectOne(wrapper);
% x" U) N8 v, ^! W0 j& c    // 转化为Vo$ e" [# Y) x' Q$ s/ h
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);+ m+ A- A. k$ K+ S
    // 从其它表查询信息再封装到Vo
$ H8 b" [4 V. f" Z    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
# E" u7 R" R, ~5 i6 i8 b+ L    return userVo;1 j3 P1 Z4 f% h0 V% _& \2 B3 B" K
}. {6 }* {% i/ r, B" S1 T
</code></pre>" q" h( T4 ^) O* r
<p>附属表信息补充</p>( ]! F, H2 k% R
<pre><code class="language-java">/**# _& ?+ m1 D* @  ~5 z5 M
* 补充部门名称信息7 O, V: T; S9 q- r0 p
*/
3 s3 D7 e3 d0 d5 Z: C, V3 Mprivate void addDetpNameInfo(UserVo userVo) {
# M9 k. w1 R5 w$ N- T+ B    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
7 L+ p) @/ i$ B0 F) w9 K0 _4 \        .eq(Dept::getDeptId, userVo.getDeptId());  ?( x6 L! Q( x3 S  K3 T8 I
    Dept dept = deptMapper.selectOne(wrapper);6 B* B+ q: N9 h# r$ n# a0 Q3 ]" K
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
8 f; I( T( g4 C8 ^% |+ V- p0 V4 ~}( N2 H/ d/ {$ J: {4 A: P
</code></pre>
2 g5 B' G: x0 W+ W; {- f% g<h5 id="2理论分析">2、理论分析</h5>* s. H0 q8 [" H# F
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
* |) A; r# i# I8 `# `: p<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
# _$ K7 _9 `% E9 ~/ V<h4 id="二查询多条记录">(二)查询多条记录</h4>% a9 X' v4 |6 Q
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>6 p+ U& y3 D. J; m& o- ?9 n9 P
<h5 id="1示例代码-1">1、示例代码</h5>0 r7 y+ X' j/ B6 e4 o6 V( A
<pre><code class="language-java">/**
- A, f  W! n4 [) h, P * 批量查询学生信息(一个学生对应一个部门)
8 \! i! U# ^6 s7 a+ y( E */
6 S& ?0 o4 U) X+ u& v! u' Spublic List&lt;UserVo&gt; getUserByList() {
  ]# l+ r4 c2 m5 w# k9 F/ U    // 先查询用户信息(表现形式为列表): f& D9 E0 F6 E; P5 w
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());% L9 Z+ t9 ^* t4 h+ @9 ~% K
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
8 n' \. x7 H4 x* o) f    // 此步骤可以有多个/ }5 t6 s: W" {: \' n+ Y4 Q
    addDeptNameInfo(userVos);6 Z# u* w6 t& P( Z* _
    return userVos;  ]; G% S$ X! u- V/ M* i' w& H
}
  |) B. y+ D; z4 ?) p: |</code></pre>5 @* ~. A4 A+ \$ ^- u
<p>附属信息补充</p>  \  G$ H/ O, ?) L: y( `
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {: X1 d1 U- v% n, J; S0 v- T
    // 提取用户userId,方便批量查询/ C1 Z% I* ^7 D6 Z
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
! W3 F# ?' y; {    // 根据deptId查询deptName(查询前,先做非空判断)8 c; e& v( D9 a7 \$ q$ y
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));& e# E; A7 ?4 z; o1 ?4 O5 b
    // 构造映射关系,方便匹配deptId与deptName
8 }' i  j2 O, Q8 _; V    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));4 x! Z4 L' Q; i7 [
    // 封装Vo,并添加到集合中(关键内容)
4 K. r6 m8 d% ^! j! {* [# e    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));0 J. q$ Z- A" [4 c, b
}
' h5 Z! u7 A4 w  P% p/ E) P( i</code></pre>- C/ ]  L, M' I0 t3 Z
<h5 id="2理论分析-1">2、理论分析</h5>
0 o4 ]3 P- X- V1 j& c) q; [6 U- H<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>8 j0 q0 u: X: [
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
* ?' }! C+ c8 r5 i3 j<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
7 t' \( b" ]& }" R3 b( e<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
% d* C4 k9 ^/ U<h5 id="1示例代码-2">1、示例代码</h5>
) E( v9 L1 p% `& m<pre><code class="language-java">/**
2 \$ E% B# J' ^$ y1 S2 ? * 分页查询学生信息(一个学生对应一个部门)
4 T# G/ q8 b9 P7 R% T7 s5 J */0 o9 X( A1 u! n. ^& Q# f$ F, _  W$ _
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
! f* ^. N, V) v0 Z* E    // 先查询用户信息
, X% e4 _5 M0 i+ k* n    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
! z" _, I. _9 k+ W. N    // 初始化Vo
" Z1 A. e" @+ r! o/ {8 m* W    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
0 _& k8 Q# l" A7 |# K! ]9 _( u    if (userVoPage.getRecords().size() &gt; 0) {4 a) U6 H8 R" K7 G  D
        addDeptNameInfo(userVoPage);$ E* _5 i% h* N$ y' ~- K
    }
1 E& L6 P9 i2 Y2 a5 t3 N7 N    return userVoPage;2 d. \- U/ D! B4 c# A
}, R$ m5 C5 ]2 z) L
</code></pre>  b$ G- ~2 Z7 \* E- d) L* k0 c
<p>查询补充信息</p>
4 E# h' p% `/ @6 _<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
2 U$ o0 J  t( z8 a, a! @; @    // 提取用户userId,方便批量查询
3 c$ K( M$ S' a1 Y( T+ k    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
; r* N# t" z; f+ T' i    // 根据deptId查询deptName
. U( b, i4 N8 d3 C$ z    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));! G! \, ~- u; h; Q6 ?  ~' q; C
    // 构造映射关系,方便匹配deptId与deptName
7 C# c. ]& z( p+ U    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
3 k$ O1 H) m' f6 h* P    // 将查询补充的信息添加到Vo中
0 P6 {3 p7 `3 Z  c4 N    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));  A2 e' M/ x- H0 w8 e/ m
}
; q) `; _" ]$ A+ v* v! U" l( M</code></pre>- Q- {. D/ T) J
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>: m, T2 w. h+ H
<h5 id="2理论分析-2">2、理论分析</h5>& V1 k8 ^  ]9 A8 R% Z! t: A
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
9 `8 q/ p, }: m4 }9 g4 T9 g<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
, T: H/ e: c8 O0 S  p1 K<h3 id="三一对多查询">三、一对多查询</h3>
! \# F5 b6 S. P<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>1 `5 N8 {4 t9 T
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
) C* \" o1 C( O" e& k; Y<h5 id="1示例代码-3">1、示例代码</h5>
. @9 @6 Y# B. d: H. {8 g* t) [<pre><code class="language-java">/**+ ~# _, Y# |7 k5 X, T  W
* 查询单个部门(其中一个部门有多个用户)
% m% ^! w/ I: V4 s3 \' g0 H */$ t) D7 y( C! U7 w0 q, E
public DeptVo getOneDept(Integer deptId) {7 F5 L( {( w; M% B6 s
    // 查询部门基础信息3 H/ G* |5 O1 d( B; j! s: A7 Y% [
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);8 h' C7 s/ P( I. ]1 p6 q5 {( j
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
; K+ j- u. }8 W1 j% K8 |- Q" n  O    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);, D$ E: l6 w4 r' N8 n
    return deptVo;* l/ ]* a4 O* z' N; q1 e& W0 O
}0 Y1 Z8 D/ O! f. I# h- v- y' A' e" ?
</code></pre>4 E/ Z4 h; [2 r) G# h$ m
<p>补充附加信息</p>
/ j& d) V7 @  E5 @/ u" D<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
& x; n% z% n' f4 C! h! X. k    // 根据部门deptId查询学生列表! |7 k5 p- N$ R9 Q" v6 w
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());  w/ l7 x+ ?5 E- k3 h1 E/ B
    List&lt;User&gt; users = userMapper.selectList(wrapper);
& o. r% v7 F3 i/ S2 E    deptVo.setUsers(users);
  F* [7 n* L) S( }" ]}% Q0 ~% y* g) \. `1 L6 {. E) q
</code></pre>
3 Q3 G4 G: U9 P# z<h5 id="2理论分析-3">2、理论分析</h5>2 O' ]4 E* F( _: ?8 \
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
8 g9 u0 N5 j5 |! _3 j<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>! V* {( A3 d$ f" M( z: x2 y( F
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>) r  G4 G; {  i( v+ k5 I
<h5 id="1示例代码-4">1、示例代码</h5>
/ R: q4 X. Z3 b* T) y5 ~<pre><code class="language-java">/**
) V2 w& }" |( ]! D * 查询多个部门(其中一个部门有多个用户)
$ W+ T: q6 J& }" o6 u. A& ]" O */, h$ g3 U- h0 _! W+ o3 q, ^6 b
public List&lt;DeptVo&gt; getDeptByList() {) G: f  t1 d: w( ~8 ]8 v
    // 按条件查询部门信息
; C6 N0 U/ j5 Q$ ?6 O% h3 A    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());: R7 _  g4 n! t% b
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());& i( B9 v" W" l" P, N3 _
    if (deptVos.size() &gt; 0) {' S- k, M# b. u4 o  v& p- z
        addUserInfo(deptVos);
1 v) z6 Q" j% }8 A0 B2 T% D% h    }
6 F6 t/ E/ P" I& l* e  N    return deptVos;+ ^2 L/ m/ K) A& W; T: P
}
. |' o, r: M0 l/ E</code></pre>
8 J7 v7 ~; n0 U9 }' B* A<p>补充附加信息</p>- ?% k& m6 `" x7 V& |
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
* C* c3 ~* y# @( P  F) _0 c    // 准备deptId方便批量查询用户信息6 E3 q- D" d  y6 B3 l7 Y( a
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());9 n& ]; s  X8 K3 N
    // 用批量deptId查询用户信息
+ w/ {  f! m- v) p/ S! T9 j    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
% {" i; h" ?' [& g/ b/ e$ \    // 重点:将用户按照deptId分组
2 O) w+ z* a7 p: h& ^  Q; c    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));1 }% g4 @0 r8 A- G, N: F/ e
    // 合并结果,构造Vo,添加集合列表1 S3 b7 G/ v1 Z0 Q
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));( {  x7 m7 }( H6 i& W8 q
}
/ ?5 R: t9 o+ V</code></pre>
5 a; x1 T* s% H. f" a8 {+ S3 |# I' v! z<h5 id="2理论分析-4">2、理论分析</h5>* u* @: {6 w. f) ~4 C
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
% |4 X: i" j' o' g<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
% r7 P# b: i7 y  J<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>9 f" a. m3 k2 v& c
<h5 id="1示例代码-5">1、示例代码</h5>0 Q4 ~" v6 B- `
<pre><code class="language-java">/**: A% s, X6 C; n& a! K; u( Q
* 分页查询部门信息(其中一个部门有多个用户), N6 d% l- G& {/ U& l/ C8 p
*/
# x6 s3 x2 E7 i) D& ~! i, }public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
( G# j+ A& h+ D0 ]! l# C8 |    // 按条件查询部门信息
5 e, K8 Y  ]  j. D    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());5 ]; v4 W" q5 U7 ]
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);+ ^% P+ K" C6 H# e. f. `2 A
    if (deptVoPage.getRecords().size() &gt; 0) {1 }8 @/ T( N0 E6 ?$ Z0 v6 R+ B* Z
        addUserInfo(deptVoPage);
# w0 `  x, r9 l2 O1 J* d6 ?, \    }8 [: y: X& N) G% q: J; D
    return deptVoPage;9 q- \) ]9 X5 p( v& X, N- _9 i: w
}
6 t  a% k$ `" n; p* L0 n* j4 d</code></pre>! g2 _; B! q+ b' D/ [% y
<p>查询补充信息</p>/ u7 n" {+ R* J' S  e3 |
<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {+ _, q  d% _; L5 E/ \% j. o
    // 准备deptId方便批量查询用户信息
2 _* W8 H% P$ _    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());5 {' f8 d- f0 M, w6 J( i' o
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
& X8 j+ |6 l( M& a/ N    // 用批量deptId查询用户信息! }7 S7 Q5 \* N5 s2 N; i5 M1 K
    List&lt;User&gt; users = userMapper.selectList(wrapper);
0 S; x: y  j+ c$ j    // 重点:将用户按照deptId分组1 a" ?+ ]2 `& E+ k, T
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));: s, D+ M$ z+ z% a1 z$ G- Y% d) Z! c
    // 合并结果,构造Vo,添加集合列表
9 V( L1 Z" z* n, g  m    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));3 q2 G: q5 B! V" T
}
4 s7 f0 N1 b+ X1 q, B</code></pre>
9 R' r( k' f: u0 C/ {4 Q<h5 id="2理论分析-5">2、理论分析</h5>
; \% c, [) S. z' j9 _1 r3 G<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
4 N2 l' W4 n& F6 R) L# f8 N! G* A<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>3 ]$ I" m, H, [2 R
<h3 id="四多对多查询">四、多对多查询</h3>; s# V+ C* |3 R
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
( s3 o$ b% W( V<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>( O  }5 i% j. c  ?* N
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>1 ]2 c1 {9 b3 X- S" q/ T
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >" Y: K: V4 S9 V2 M, f: J2 z* u+ b
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
' Y0 _! Z  j: H* J" F' u<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>( O( z* M5 C3 X! u
<h5 id="1示例代码-6">1、示例代码</h5>( ^5 ~7 N* w( s/ o. T) \
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
. _0 G9 B! M/ o8 l    // 通过主键查询学生信息
7 u) @& F1 x. Z1 W    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);7 [# X7 t+ ?2 Q# ?
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);# j- H) _/ H& O; M4 l
    // 查询匹配关系* p/ G6 |/ N! p8 z: C- b
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);+ [2 |2 e& \/ w+ N( L2 t) m
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
( [* J+ o2 @, X' g    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
4 U+ r% j# F0 ^$ u        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
/ W, ^/ ~! {( F$ a: |* k/ C        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);& O# c  |- L- b* K# t5 a2 P- H8 i
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);  z$ s$ _% Y) Z" S0 q2 O
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));5 h) t5 X% S7 e' R: o
        studentVo.setSubList(subBoList);
2 Q+ c4 y. B+ }1 ?9 Z+ Y% }$ M) S    }
8 F8 q+ C/ w6 t- W* I    return studentVo;6 P5 R9 w* t9 \+ t7 ]
}
" ~3 S1 ^8 Z7 b2 |; r</code></pre>, ^( Y- S* m1 B( ]8 h% M4 J; c
<h5 id="2理论分析-6">2、理论分析</h5>
5 B: ^5 D% C# j: N<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
. t: {* w* ~3 ]$ F$ y: j1 p7 a8 C  q<h4 id="二查询多条记录-2">(二)查询多条记录</h4>9 G+ e) c# r& p8 _2 c
<h5 id="1示例代码-7">1、示例代码</h5>
+ i3 G; k5 V5 H  P6 R. V) x: ~  Q<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {6 i8 t" {! B* M  A2 T
    // 通过主键查询学生信息4 C" u5 Y4 P& |) N+ D" r
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
' O4 G- X. v+ s1 f0 f: `+ r1 ^    // 批量查询学生ID
0 `1 L' e0 S- L3 C% i% W1 V5 r    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
* P& }; c: Y4 k! ~' n    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);, l; \1 q7 m5 b! S2 Z/ f9 S; P
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);" G# H% U4 L2 n( K9 O. s
    // 批量查询课程ID: ~' w0 T! R: n/ n0 U* j6 u6 K, e4 e
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
' W( h7 v; d" O: L    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {) j& \4 P) U+ M
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);. E* n/ P4 o+ m6 z3 v
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));+ C6 z* ~. R, q3 I0 w( _
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
+ }8 a# e" I7 Y4 M! p4 @        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));4 G1 G( `0 o" J+ U  t% \: I/ G4 b
        for (StudentVo studentVo : studentVoList) {
' z8 C6 U& T' }            // 获取课程列表  p: D( q8 T! u. s) t: m
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));3 {5 c% R/ M+ ^+ Q) D7 `
            // 填充分数
2 u. H5 v* D1 ~6 d2 i( Y# c            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
( ~4 R. a+ {  V; {2 O            studentVo.setSubList(list);
  n% K& b* v2 E4 k8 g. \        }
' B& l: `: @) ]; z5 ^) T    }' d4 c8 _) R; y5 @
    return studentVoList;: v2 z0 @& ]" D1 f- o4 Y% E* A9 c2 K( v
}9 }6 a/ O# M, A( q& @
</code></pre>5 s% S6 o: ?8 }) p1 K+ Q* ]# G
<h5 id="2理论分析-7">2、理论分析</h5>8 J" E8 g; g/ e" n  R
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
, |/ Q" R" ]) r3 @+ {0 H<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
  O4 F7 y5 n8 w. S<h5 id="1示例代码-8">1、示例代码</h5>6 U6 a; [( g* m. b, |$ }
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {2 q  ^. X; [- e0 o  V
    // 通过主键查询学生信息
7 k4 _& z5 N) ]. `    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
- w: H0 ]1 Y6 n    // 批量查询学生ID0 b* E' E) ]! w
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());( z& H/ o" k" Y) S
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);0 Z! L- t; ~) I/ a# t
    // 通过学生ID查询课程分数
* i2 n$ L4 X, M' V% g8 ~! ^- f    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
# I' Y3 B# o' ^1 U* w9 u    // 批量查询课程ID
9 z" {  S! B4 z- n: d3 d    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
0 J  g% Y  w$ Z$ _0 C3 z    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
: |( K, E, Y: T% a        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);  e" `% C& K4 r; }# i9 `
        // 学生ID查询课程ID组  N* c# O9 A# y6 T7 Q
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));- ~5 D" t5 l$ c8 ^
! L  K0 f+ ]$ d. O0 d- q# W1 T
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));+ m7 ?; ^2 V4 p; b$ j% ~
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
$ D& n/ D5 j9 A        for (StudentVo studentVo : studentVoPage.getRecords()) {
4 @6 J$ J, o! b, J* T            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
) I" q' l5 ^! y            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
$ s1 d5 g5 x8 {7 B            studentVo.setSubList(list);0 V* r4 p' N. Y* L0 ?
        }$ \5 K2 J6 Y" u
    }
& [6 W8 F9 p0 n    return studentVoPage;7 J- R- y+ U; C5 K0 u$ g
}
  j/ {- s  r* p1 T: j</code></pre>
7 s8 R' ~5 \' I8 @5 E2 v<h5 id="2理论分析-8">2、理论分析</h5>% w5 b8 V. h; B% G) Q7 t
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>. t% v! h4 ]# |
<h3 id="五总结与拓展">五、总结与拓展</h3>
' ~: c$ G, T2 S7 o9 W) X7 S<h4 id="一总结">(一)总结</h4>: }* D3 F7 ?# O  }# E  e6 q5 D/ o
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>$ U% f. j9 e/ q# \# j
<ul>* R7 u9 i. o- F! H9 |3 L
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
4 c# V; C% }/ U<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>* x; \7 @1 a4 P" E6 J! L
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
+ e: M! w5 }  l# J$ o</ul>
1 B* z. S8 g4 w- s5 T<h4 id="二拓展">(二)拓展</h4>
! c  q6 e! N8 L, W0 O, o<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>. y( E. u( _# V" }! S
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
5 [3 M7 L- C5 T: v% N<ul>
2 b2 L# z4 y2 M  e' z<li>当数据量较大时,仍然具有稳定的查询效率</li>1 C( j! U1 I5 C% X
</ul>
; H2 B- R; ~' [<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
0 ]! O% e& f9 }' d0 ?: |<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>4 O9 ^% X& c' N# x0 s& B
<ul>
6 Y! I4 C* O1 K; y4 q* @( e<li>与二级缓存配合使用进一步提高查询效率</li>: ~( n; s0 ]+ Q4 }0 @% K# C
</ul>8 K& H4 e2 J& `& k$ q
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>' i8 ~) q9 M  M, x( ?/ B4 E
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
$ a6 N5 l6 s. G0 f; @# ~* F5 [1 z* d% Z3 D% G! t$ C5 }( Z7 B
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-1-10 03:40 , Processed in 0.063985 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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