飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7885

主题

7973

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
25985
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
- G5 e( p! h9 b6 z9 t4 \0 {" d
<h3 id="一序言">一、序言</h3>9 G. \4 d& O7 A# N
<h4 id="一背景内容">(一)背景内容</h4>
4 F/ A, Y* B6 H$ H% @<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
7 X; \8 j+ a- f$ g0 z<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
. l$ m1 M; T' M8 l9 n  [<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
4 |2 {+ D, Z/ y, m<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>3 v2 I+ p! S% M9 y6 j8 _
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
2 y2 J( G' P3 V3 Y1 T<h4 id="二场景说明">(二)场景说明</h4>
5 Q: P) E2 R  \2 C% i* B<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>3 H; x# w! N: N) _+ x
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >0 G' C/ O5 D% v7 F" y" u
<h4 id="三前期准备">(三)前期准备</h4>
8 B! g: D7 ~/ f. [$ c( B<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>2 c$ q7 T  c; I. e" ^1 g) z% _7 w! U
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >1 S5 j/ f5 k. c! K2 ?
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
4 }) P8 E" {1 i7 ]9 P+ }7 n4 L<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
& T! J+ W/ P6 E  }: o<h3 id="二一对一查询">二、一对一查询</h3>, B# Y9 `7 G( L" x. W
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
7 c8 Z$ l4 W  V. S' f) }<h4 id="一查询单条记录">(一)查询单条记录</h4>7 Y2 m3 p6 s5 J7 h' O, n
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>% g1 \/ m( h' s; P3 `
<h5 id="1示例代码">1、示例代码</h5>
, X" ~. }1 }2 I6 A, Y( B. B<pre><code class="language-java">/**
; `: C1 I5 Z! d. F * 查询单个学生信息(一个学生对应一个部门)* R+ B; q6 D0 J7 n( V! v5 s8 ?
*/
5 B# N$ ?$ @+ g9 F! s. ]: M7 u; m  ypublic UserVo getOneUser(Integer userId) {; w: w8 j0 d/ _6 U* I5 Q
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)3 ?% `3 s8 H# M2 W! y: Z$ `
        .eq(User::getUserId, userId);$ V- K- o; ^0 \( x) o
    // 先查询用户信息
3 M  J% O! g5 O6 u    User user = userMapper.selectOne(wrapper);
" ^9 B) f/ B# v. v0 R: s5 Z/ i    // 转化为Vo& }  e. E, y! A! G
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);  v, R4 v) e4 F$ L! [5 W& h+ w
    // 从其它表查询信息再封装到Vo' M9 w! k( ~5 ~: F8 _" e. n
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);6 [+ k1 K$ A3 b3 @
    return userVo;
# E  w9 z) c* l& Q$ f2 N8 m! ^. s}5 E% Y" J/ m* j9 E$ K
</code></pre>
4 I# a: M2 S" V% D<p>附属表信息补充</p>7 ]0 i1 I! h/ i+ n8 K
<pre><code class="language-java">/**
5 o5 ~% m! ?, t * 补充部门名称信息
5 W: R& g( D/ \ */) a- s7 ^* L) h$ a: I. m- q8 w% ~
private void addDetpNameInfo(UserVo userVo) {$ C7 M9 y6 f7 A% ?' {/ k
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)! i% Y3 z, [% [* I: T0 _3 W/ I
        .eq(Dept::getDeptId, userVo.getDeptId());& R6 b6 L6 v& b
    Dept dept = deptMapper.selectOne(wrapper);; c) S  g) L* h
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));. F" d  u4 w% W
}
7 X* o! [( c: g</code></pre>
1 z2 c( @( i: @- I$ N<h5 id="2理论分析">2、理论分析</h5>0 X) _' @% D5 }7 R8 q4 ]
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
9 r4 R4 a- m5 L: M: ^, ~<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>& ?4 l. |& q$ t1 m2 f% P
<h4 id="二查询多条记录">(二)查询多条记录</h4>& @6 D8 j2 ?, t0 ]  C) r4 E
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>- g# V# x7 R' t
<h5 id="1示例代码-1">1、示例代码</h5>
# y) f6 Y3 y! n: f<pre><code class="language-java">/**' B, p$ V- I! D# t5 y
* 批量查询学生信息(一个学生对应一个部门)
) K/ e( ^* W5 Y; N0 W; q; F */8 V( F! i. j) y
public List&lt;UserVo&gt; getUserByList() {
/ j2 [1 S2 g( B; z    // 先查询用户信息(表现形式为列表)1 o; p9 Z/ H# x1 L" z
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
! r9 R; ~  G- @" P    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
4 U. q% M! w6 H0 Z3 W; Y0 h    // 此步骤可以有多个
" s  p; T. Y% _% N4 e# @6 I    addDeptNameInfo(userVos);( A) i' O5 j7 Y* F; g3 x
    return userVos;
- ^1 O4 X; |8 R8 c' _* R# |}4 E/ [) M* H' R' f4 v9 n
</code></pre>* m. C$ D/ Y4 u7 `3 s1 N6 f
<p>附属信息补充</p>9 w/ v+ P6 d+ a5 j) f4 _' K% }6 [3 A
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {3 e7 H. N: [% i9 \  l" X
    // 提取用户userId,方便批量查询1 i( p9 y! n# g5 ]' a/ g
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());- s9 |$ E9 v  U/ U, f8 m+ g! ?( {
    // 根据deptId查询deptName(查询前,先做非空判断)$ J0 e/ q) i3 o- b, n0 Q, ~
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));% i8 Z: }* w$ F9 k% ~2 g' D7 c
    // 构造映射关系,方便匹配deptId与deptName5 v6 B! |' v7 Q- ]8 \$ \# e- o- W' i
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
  C9 v1 p  g$ v3 c/ Y" f    // 封装Vo,并添加到集合中(关键内容)  E# r3 v- h" h2 Y
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
/ N1 D+ P& j% x( F4 U# v}
& T) n! {+ |8 q& A6 M/ J5 ~; h/ x</code></pre>
% ?. H( L: Q& x; H5 l. K<h5 id="2理论分析-1">2、理论分析</h5>, M0 t9 W. V4 _3 I- S
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>* z6 N. T4 _  D) A( ~; N0 S+ G, P# S
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p># O; I3 G- v8 _4 g0 a! p
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
& x' ^; K6 i6 a* h" U! o* b<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
3 B2 {7 ~. e' h! ]) O" {' V<h5 id="1示例代码-2">1、示例代码</h5>3 D" U5 L4 _! G
<pre><code class="language-java">/**
/ h7 _- x6 O/ e1 M5 z# F; A. w * 分页查询学生信息(一个学生对应一个部门)4 L4 U& w0 ^% Z$ U  t; w& s
*/
7 m( j9 W+ ~8 f; r- j( `+ a) npublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {3 c4 t8 r4 \7 |: _! o3 w
    // 先查询用户信息( k+ B% W1 A5 ~4 N" }$ @
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());( [4 s+ ?" W/ |3 w
    // 初始化Vo5 K' L* Z) @" @( B/ K7 N
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);4 |* \" _- K/ M0 V" p  q, G
    if (userVoPage.getRecords().size() &gt; 0) {
2 E) n9 q$ J  ~6 u        addDeptNameInfo(userVoPage);
# n! Q9 F6 U: K+ W    }; V) e6 [# u# N2 v
    return userVoPage;' Z( D+ F# b1 n* I% U. k( Y& S. [; C
}
1 ~- ~1 m" B/ g3 x</code></pre>
3 q8 }) B0 j/ C( {% o, Q<p>查询补充信息</p>2 h. a; q  ?/ U4 \2 r1 t
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
' z/ e6 k; g8 E( k6 S- ]# z* |1 J    // 提取用户userId,方便批量查询
! r4 I" v: {( P% G# I    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
- q; E5 e! a. G1 d" K    // 根据deptId查询deptName# s6 M0 P" T+ l3 i. ~
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
9 {+ c% h' k# W" a1 u" D    // 构造映射关系,方便匹配deptId与deptName
6 S# N: _& Q; m) h( m( v    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
: ~6 L& f6 o& {% P' {    // 将查询补充的信息添加到Vo中* d) W) P; x2 _3 J: M# Q7 v( R" H6 D
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));' n2 Y  m; b/ m' m
}
$ P) @5 a, w- @- h</code></pre>- H- u4 I1 k" q4 m! f
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
2 \  z6 m  f# ~% M( v<h5 id="2理论分析-2">2、理论分析</h5>
8 K$ Y- H5 M) o* q  d<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>& ?& o7 O* E4 I8 B  K9 e5 @
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
9 \- p5 `* ?4 D; g  k+ n7 G<h3 id="三一对多查询">三、一对多查询</h3>" S7 M' j+ M0 r" {% ]( u
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>2 ]: e  R* l- U
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
# d4 ]1 s  O0 F6 A) }7 P& g2 V; W- B( `<h5 id="1示例代码-3">1、示例代码</h5>
3 J" z& ~: H: Q* T- _( h! M9 q<pre><code class="language-java">/**5 J( g0 j+ O; Z" {4 F" O
* 查询单个部门(其中一个部门有多个用户)
5 _$ V" B- D" ]8 _4 A/ Z: U */" y* Q$ a. V" I& a
public DeptVo getOneDept(Integer deptId) {
6 _; T/ |9 B) o# v! \4 F    // 查询部门基础信息; P8 P0 S4 r) v+ g6 S& C
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
: j5 p* z0 p" ~$ _, Q! @1 X2 y    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);7 M. W, _) i, F: E
    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
2 [3 W9 P' W8 t& q9 G$ O    return deptVo;7 s, }$ J  z1 R% c
}9 L. W% p( G9 O( i8 u! f
</code></pre>5 z2 w9 _. a% ~5 S! s9 D0 |
<p>补充附加信息</p>
" [0 V9 L6 V+ Q2 E9 {<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {7 y8 q2 \( S8 T+ M3 f4 h" R( Z. Z
    // 根据部门deptId查询学生列表
! Q8 c1 z$ U3 J, F, ?( w5 R    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
8 E  S0 i& Q3 u4 L# B3 F    List&lt;User&gt; users = userMapper.selectList(wrapper);
/ Q( s3 n6 R  j- U/ ~# \5 S1 \    deptVo.setUsers(users);
* Z7 g2 M( @4 E" r, P" ?8 A2 v}0 k( G3 K: g9 G7 s" t1 \, ?4 l- k
</code></pre>
7 T: n0 d$ i- P9 c<h5 id="2理论分析-3">2、理论分析</h5>
) A/ s/ }' T; X( M0 {* {  i<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
* ?  ^# F  m6 P8 O1 T6 P8 n: y& q/ Y" W<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
: V; U2 g1 Z" u' t<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
+ q. J/ h* r- l$ G- d<h5 id="1示例代码-4">1、示例代码</h5>
; V7 V6 V7 P* e  G- X! w  n* I<pre><code class="language-java">/**
& `7 w  a7 P1 E2 M& `; v; c# u* q# O * 查询多个部门(其中一个部门有多个用户)* _+ m! Z+ i% D. D: }' @
*/. y7 ^1 b3 M0 Y7 G+ T, n, m! }
public List&lt;DeptVo&gt; getDeptByList() {
. ~' t# _" h* N5 T4 T$ ?    // 按条件查询部门信息
' \) ~  ^$ Y8 i    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
8 ?# U8 O3 o2 D0 ~- m8 S9 u- k! ^! Y( \    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
9 {! c: u+ c# ~1 Z3 _    if (deptVos.size() &gt; 0) {
4 Q" p; e6 G9 w  t! W# G5 ]2 U        addUserInfo(deptVos);
; J! O- T" L4 W    }. c) _+ M3 M# I
    return deptVos;( `4 A& d4 j, K% d+ w4 \2 t  M
}
" @$ m7 \- Q5 @$ E! f6 n: V! G) b</code></pre>& w2 r9 q* e, b  T9 K- b# P
<p>补充附加信息</p>7 I! X8 {% x& B( z7 |
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {. t; M0 \+ v8 Q
    // 准备deptId方便批量查询用户信息
/ J) v/ {% h: }. y$ C! |4 m, J  E    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());* T  X) _: G: f* r- Z: Q9 f
    // 用批量deptId查询用户信息
  O3 A5 F1 u) x! g    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
( Q5 N' N; @; ]) X) ^$ E3 f    // 重点:将用户按照deptId分组- N* S! i/ n* e2 T5 t$ X& J: j% H
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));$ X- y' l2 R4 ~" Q% R0 r* V% p: S8 d
    // 合并结果,构造Vo,添加集合列表
+ D: B  S7 u! i8 Z4 L/ e* C    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
9 H5 \+ B, f- ~/ I8 G}
0 Y* p8 I# \2 ?- A9 _</code></pre>
* D1 ^4 p# ?8 z5 P<h5 id="2理论分析-4">2、理论分析</h5>& X% L$ X+ I: D1 o  c( q
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>2 _( n0 T& \( Y& b+ e% B
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
3 X; ~# U/ E- b' A<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>' z3 G& e1 D' l) }
<h5 id="1示例代码-5">1、示例代码</h5>! }1 v, k2 O0 o! b
<pre><code class="language-java">/**7 {6 W. p" L, I# v. K5 l9 \
* 分页查询部门信息(其中一个部门有多个用户)% J! t) v) |# _8 y  N+ H
*/
# t3 H# ~2 s9 _% G3 z- Qpublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
2 s. `9 N% m  w8 c    // 按条件查询部门信息2 m( x( e6 `+ d$ C/ A. U
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
9 d4 E! p- n: T. Y% d1 j    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
3 v. Q( f& l5 q* [6 v+ k    if (deptVoPage.getRecords().size() &gt; 0) {/ A; E- ^' t  i( `2 H5 e8 E5 M+ y
        addUserInfo(deptVoPage);1 T* c5 o5 q% T
    }! [9 J# h) m4 T2 Y7 K& ]/ D
    return deptVoPage;1 B6 f9 L, n. A5 t7 c" e; G
}7 z' Z1 B' d1 u
</code></pre>7 k. `+ n6 O' \. o$ I$ ]; [
<p>查询补充信息</p>
3 R% M: {+ p- A2 J<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
6 w. ?5 [/ Q* \+ ^5 e% w* b    // 准备deptId方便批量查询用户信息
6 x0 M1 y1 D/ V7 |    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
% H7 k: s4 p. I5 s' V! r    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);1 ~- q; v7 l$ i
    // 用批量deptId查询用户信息) z% U: e, b% y4 S" r
    List&lt;User&gt; users = userMapper.selectList(wrapper);1 l3 f) }) N; o
    // 重点:将用户按照deptId分组0 Y& \' Y# J) s4 P3 @
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
& I7 u; y$ n( k- ^+ y; ?5 P  r* O    // 合并结果,构造Vo,添加集合列表, N& ?0 [( E5 i2 F4 m6 V2 u" W
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));2 j( ?  \7 U. s4 t2 d( Z/ W
}3 M- E# B: g7 L" n: ?" A% s
</code></pre>9 \. T6 Q) p. Y. ?; X
<h5 id="2理论分析-5">2、理论分析</h5>
& X/ w- I7 G. {4 ~  V% X4 [- J<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>% U3 I; q4 _3 u0 s. z. Y2 n
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>8 W3 e7 y8 a; O
<h3 id="四多对多查询">四、多对多查询</h3>
7 J" @  c7 K: q+ h/ K6 q; B<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>1 J/ G2 s7 I; O5 Y: l6 C' N
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>( G9 B7 J" N& f+ P7 Q
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
, D* b) i& a1 R! j  @& U' C# M  n+ o<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
, z; y7 m4 D( k1 @+ T3 T5 j<h4 id="一查询单条记录-2">(一)查询单条记录</h4>- V; R% R. X( r! N; M
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
2 e1 r0 U! n: x1 H8 J$ J<h5 id="1示例代码-6">1、示例代码</h5>& n' b: G0 o$ t5 x
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
1 d; O4 h" X" F. Y# s    // 通过主键查询学生信息/ S9 D" _, P) h( ]
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);- Z6 r. ~  W) C
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);8 {; a( D1 I8 j: q; n; Q
    // 查询匹配关系
8 F4 h" D4 c8 t+ V    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
/ Y4 o, H# b7 @( F: v) f5 w    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());% G3 k. u/ E) T/ Q% c* L
    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
( v9 ?7 n( K+ z3 j" |( g        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
# t8 R- y  a" e5 Y1 m' [& C9 U4 P" h        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
/ ^/ k8 v9 e4 T& ^        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
( M0 n$ w+ {' e3 T( M        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
) F+ N* A+ s; e- g6 Q        studentVo.setSubList(subBoList);
! r2 M& ^5 r* l: ]    }" g) u& C; ^6 o, [- {
    return studentVo;
8 |! u$ Q3 x1 U: J}5 B! R8 B0 M& e2 a! l
</code></pre>
) D" m# K& f. i8 p% H+ B<h5 id="2理论分析-6">2、理论分析</h5>
* e) }! R6 V4 E$ ?<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
! c0 v2 U8 w6 {7 w" D, x. p, `/ m<h4 id="二查询多条记录-2">(二)查询多条记录</h4>6 t0 }% r) X' I9 s  h+ y2 l
<h5 id="1示例代码-7">1、示例代码</h5>
0 H7 h; g7 M, a* s. f8 k6 }<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {- U) y: @' j9 n$ p. e/ N
    // 通过主键查询学生信息: ?- j$ [- B' w$ M: X2 n
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
3 X9 P; B- J8 W. P+ k    // 批量查询学生ID0 ?; y4 Y8 ^4 ~
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
1 _# o- D* {0 a6 T    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);3 t) b' t9 W3 R/ _6 p6 t
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);6 s4 K/ s6 Y' Z9 A* G# J: ]
    // 批量查询课程ID- W$ r- W" @% R$ c' Z+ |
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());* p. X& b% T5 k% ~6 Q  X3 T+ a
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
6 U' {/ s% h- v/ Z3 W3 s        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);: ^! R3 D, D8 t- e
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));. Y( `, }' v8 i
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
% V# ?$ |( J  Z! ^  t        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
5 M/ @* a6 ?! n3 m( [: `        for (StudentVo studentVo : studentVoList) {" M" N" |2 Z. r
            // 获取课程列表
8 L* [) {! M% }$ O            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
6 F- H& h7 L7 ]            // 填充分数1 m7 l8 r! f( Y& |1 O- M/ J8 G
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));$ U+ p: a6 p! {& Z1 z+ n
            studentVo.setSubList(list);: u+ e) ^- F, P- F! N$ N1 O2 y
        }" ]- a) e/ H; S. r- m/ _7 D( K
    }; ~( I) T$ M: C% O6 _
    return studentVoList;! _. s2 s) ?3 C5 l! u. a8 U: g
}5 c: ^' u; K8 e9 z, R! P( t
</code></pre>
# [4 w0 \4 Y# ]% w% J<h5 id="2理论分析-7">2、理论分析</h5>
% X# @1 y& X, k<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
( T, A( {2 H6 E3 W5 }. G<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
' l* D$ A$ [3 z! G3 K1 ^<h5 id="1示例代码-8">1、示例代码</h5>4 W6 J8 X% A! O: Z
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {) @8 c4 m; c0 ?: r9 ?5 b
    // 通过主键查询学生信息  K- e! ]/ }2 R! E
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);7 M' k4 r7 G0 o$ @0 Y
    // 批量查询学生ID
- g6 u4 m. r# e: S; l' F9 @$ C3 I    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
  C1 Z% U" Y6 V# g: W    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);! B* a3 \% n- p. }
    // 通过学生ID查询课程分数
( t% y1 @5 O8 z5 a0 W  w- U. M" @8 w    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
% O# M5 Y: U" j0 B4 ~    // 批量查询课程ID
5 g: [" m8 H9 O. [) L7 z. n( s* I    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
7 C2 B0 O  r# w& X7 e( C5 t    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
* |1 s7 C+ h, U        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
9 q8 x4 [8 {, q5 Q  o        // 学生ID查询课程ID组
( }* g% W. X+ K2 ~% e! s! u        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
9 b, O; R& M) N  ^' X: f* }. Z* _0 n' p- K
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));8 k! @, P- S/ W: @) ]( f! z
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
, W0 n& J7 {- V. w2 L6 M        for (StudentVo studentVo : studentVoPage.getRecords()) {) |. U4 X: b9 w5 s
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));9 H. f3 |) Y8 C" p+ ?- @
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));% P- f8 l0 E" Q
            studentVo.setSubList(list);; a+ [! K8 u2 F1 D
        }) X8 C' c/ k0 P5 M
    }" e6 [6 t' ]3 [) T4 T
    return studentVoPage;
% s. ?( q7 s% ^}
) u) {: `. \8 h! o</code></pre>! v5 p- ~' L* B* j9 [
<h5 id="2理论分析-8">2、理论分析</h5>! A# P/ j7 f1 z% I; G1 c9 f
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
8 h6 o. `7 u" g6 s- R<h3 id="五总结与拓展">五、总结与拓展</h3>) ~8 ^( t( U$ `6 N! T
<h4 id="一总结">(一)总结</h4>
, {) x/ a) ~# V, W5 [<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
0 `0 j" S0 D& v3 {$ e<ul>
4 m# `2 Y3 l! E. `<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>  g  T% O! }5 F! t" `( K
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>6 c: i  x) i  w) B0 Y/ U
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
# s$ X8 R* I# M3 H8 [0 E</ul>6 G9 i" K9 C0 b& j
<h4 id="二拓展">(二)拓展</h4>' {5 j" {5 G& d$ i2 q
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
6 s2 R  h: a) g1 ?$ Z<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
3 k; _2 k! g. l$ y<ul>
* l( `' w7 E$ R2 T! j<li>当数据量较大时,仍然具有稳定的查询效率</li>5 A. {  B% Y- o+ Z% Q* E3 q0 y( F
</ul>" y2 d" G& D2 F3 D
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
& X+ r' G0 x# d7 g5 E<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
: F( |) d8 ?, A9 M4 n1 B+ a5 M<ul>
6 ?; i9 |% A: r. `8 y/ O- Y<li>与二级缓存配合使用进一步提高查询效率</li>5 R! m/ Z2 N% Y8 H. G# ]
</ul>) z: [8 g  \/ w3 G1 b2 R
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>  N0 \% N$ ?9 n, |( D* W+ j
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>8 i/ I/ B4 ]8 r$ [
5 |9 ~0 K4 ^  O5 m
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-11-16 21:35 , Processed in 0.065323 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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