飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8143

主题

8231

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

5 D9 k( `4 O$ H, u9 L9 z  c. @<h3 id="一序言">一、序言</h3>' `$ ^, L! [5 p2 d  M
<h4 id="一背景内容">(一)背景内容</h4>
+ H# O/ k2 \$ t4 Q- e9 h9 y<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
9 Z( a7 x; L" A6 g& O<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
6 g+ B% b% k% f* h<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>5 A1 O# q4 w. m( }; R) Y
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
0 [/ |% V4 O/ c$ k% Q# B; ~<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
  G$ I" K& X6 N5 F+ n<h4 id="二场景说明">(二)场景说明</h4>
& x+ y$ g1 \- B' m<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>! H8 |' M! |" U: Z9 l5 h
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
" i0 p+ j( I' N7 o: l<h4 id="三前期准备">(三)前期准备</h4>. \# D) @/ `6 ?
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>& M  R7 p( |+ n7 d  P. P
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
8 |8 Z" r1 u: j# P9 p* \7 I<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
8 P/ c, L/ o$ L; ^; ~" v<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
0 J; N- k( E$ i<h3 id="二一对一查询">二、一对一查询</h3>
) r% I; Z5 S- H. w$ a- a<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>! P) Y' L0 y- Z4 \% M4 z" o
<h4 id="一查询单条记录">(一)查询单条记录</h4>% Y6 N- T& x# x/ \6 m) W, a
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
; w% m% U5 J/ t" p# k- N<h5 id="1示例代码">1、示例代码</h5>
* N; R: H7 L$ |, _3 M# w2 D<pre><code class="language-java">/**
3 c; D3 ~; I& X6 a * 查询单个学生信息(一个学生对应一个部门)- P. y6 _2 y  o  N
*/$ r6 v% |. e, ~! z' {+ e
public UserVo getOneUser(Integer userId) {0 k+ C' f6 \5 l. z/ P, z6 P6 g
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
1 O. v' S* [- \( k/ b        .eq(User::getUserId, userId);5 O6 P, g) X- T+ Z! u/ c: V
    // 先查询用户信息1 {7 ]4 n7 F* Q( S4 _
    User user = userMapper.selectOne(wrapper);9 m' ]3 ?" |( G3 }8 I
    // 转化为Vo( B* F* `' t9 P7 L
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);' L4 K" n! S  Q4 X( _1 L
    // 从其它表查询信息再封装到Vo
1 [5 Y3 d6 [" |) n' @& U$ R    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
) `$ T  H& ]6 a4 w/ q) O4 T4 J  V* _    return userVo;
; c( `& m: z2 s9 A! v5 V& @" k}
; {( {1 {7 l0 S+ E! i/ E</code></pre>+ v2 {' s& a" P' v3 e
<p>附属表信息补充</p>
, Y3 g! K5 }" ~+ S<pre><code class="language-java">/**, L7 w, j/ J% _. Z5 ~
* 补充部门名称信息
, b' c0 F% k* A) g* J9 L9 o */
/ D) T! x8 D3 f! B/ T" sprivate void addDetpNameInfo(UserVo userVo) {0 I2 k  B1 x! F( w
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)6 I% a6 |  S4 s6 V/ k0 d2 o1 a
        .eq(Dept::getDeptId, userVo.getDeptId());
! e; s2 J; W9 `4 Q; E  E( ]" P' w3 ]9 A    Dept dept = deptMapper.selectOne(wrapper);$ A, e+ m# Q2 ~, \
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));' D& }# r5 ?; }& [' H$ v  Q
}8 q& a9 w: X8 g( d+ K
</code></pre># ?3 U; Q% U! X, @1 [# g
<h5 id="2理论分析">2、理论分析</h5>
# E( I1 f, d8 N9 n8 m<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>9 G4 S; j) d4 K1 j
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
$ m0 f. T) t7 p! a' p<h4 id="二查询多条记录">(二)查询多条记录</h4>
: p, f! e. R2 ^<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>4 B3 m3 Z  h, E4 \9 J7 p' f
<h5 id="1示例代码-1">1、示例代码</h5>6 s9 G$ U- H2 a& o+ t  M
<pre><code class="language-java">/**0 X3 `+ g4 W' \6 P6 w; v
* 批量查询学生信息(一个学生对应一个部门)
) F& H- C1 E) N  G0 b* `# H) Q */: S, D! r) j. ?. Q6 O+ G" B/ J9 A, b, t& _
public List&lt;UserVo&gt; getUserByList() {
- X% w/ Y1 d: C4 f; y% v8 |    // 先查询用户信息(表现形式为列表)7 e$ w+ R9 p$ G* u; o- C
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());- p* F' T6 E1 C! o; x
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
& `5 j1 F0 Z" j8 u# m3 B/ S$ _) r' n    // 此步骤可以有多个
0 L$ t9 }5 l% B    addDeptNameInfo(userVos);
% M4 m! K/ Y) X" D2 ?- `, A  n: |    return userVos;
) e: x7 Y4 d$ m* v5 r+ w}! c- x0 G8 i% V% j
</code></pre>: V& F  W# m: H6 N5 D: S
<p>附属信息补充</p>
4 K! P: G% m* O; M0 Z2 ^<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {7 C% S- M: x1 Q+ J+ e$ U' F& L. H
    // 提取用户userId,方便批量查询+ b$ {4 Z3 m4 e- }& K& `
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());$ O4 l/ l% Y7 c" j
    // 根据deptId查询deptName(查询前,先做非空判断)$ L$ P# X+ B- x9 N6 G$ Q
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
/ H& s: Z7 c0 O    // 构造映射关系,方便匹配deptId与deptName6 T# ]8 ^5 Y9 c
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));8 Y% W% P9 j# r7 X
    // 封装Vo,并添加到集合中(关键内容)
4 M# b8 v& N  }$ K* [4 z    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));: S% |% p0 S/ H& ^
}7 h" q  F; c0 f
</code></pre>6 I' y8 |. g" S9 g$ ]! J
<h5 id="2理论分析-1">2、理论分析</h5>
) K2 c3 ]) h( V6 t<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
, O7 f7 g+ I) }* d3 a<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
7 c8 k$ R# q7 ?<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
  l5 [, T- l2 N! K<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
- v1 e0 s6 [- f1 L  b0 C<h5 id="1示例代码-2">1、示例代码</h5>
8 i' K2 v( R4 R" ^<pre><code class="language-java">/**  l3 f/ ^8 P& _
* 分页查询学生信息(一个学生对应一个部门)( B, T+ g" y( t
*/3 G" {1 `! k$ k6 B2 r+ f" S
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
! b8 F9 |9 |1 v5 |- \    // 先查询用户信息
$ w9 ~- J. b6 x) O    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
' [: f7 M" L0 A6 q# m* I    // 初始化Vo. ^- b; ]5 s$ |3 A
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);; v" u, u+ Y! Z( x, ], c
    if (userVoPage.getRecords().size() &gt; 0) {
7 A7 e7 l( {. @        addDeptNameInfo(userVoPage);4 D$ U( v/ D$ B3 r5 K1 [
    }
  A) ]9 n; D1 h7 a    return userVoPage;
  \3 f4 e# V. V3 f1 t}* |9 l- v5 U( [: T
</code></pre>; D! u/ l; F6 [. A( j  E
<p>查询补充信息</p>
5 }% Y5 u/ i. k, x  w8 G+ S<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
- p$ x2 _* M3 o; u' x* p* Z( t    // 提取用户userId,方便批量查询
6 i7 y( x. s$ E$ |' ^( t    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
2 I) x9 C9 H( R& F2 X8 Q    // 根据deptId查询deptName" {$ q& l. a" F4 ^; W
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
' ~: r/ ]( j+ c. G4 c    // 构造映射关系,方便匹配deptId与deptName; K/ Q( J" }- S" Z
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));  c8 _+ ~4 \5 t! k9 W) A9 j3 \
    // 将查询补充的信息添加到Vo中' j. M) ^) H8 Z! d) Y
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
! U* Z7 E$ U9 V3 t9 k}- [! j) r- u0 I  d+ c
</code></pre>3 s' @( e1 X, M; D/ a
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>8 W: C+ D( T8 t
<h5 id="2理论分析-2">2、理论分析</h5>1 D4 w% b6 q) H
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>% G" E+ d& a2 P8 z+ n
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
! W9 ~0 I4 T! F( i7 R<h3 id="三一对多查询">三、一对多查询</h3>" @' G$ z: d/ f9 q+ s3 v5 v3 ]
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>& m2 E7 q4 h; ^# Z* ~: F9 g5 h
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
) _7 r9 \' e) E7 X( o  C8 T<h5 id="1示例代码-3">1、示例代码</h5>! _% Z' a0 s! `9 ?, G  ?0 b
<pre><code class="language-java">/**
5 y2 x% u& E% H; j. Y8 c  t( F4 Q * 查询单个部门(其中一个部门有多个用户). W: O/ h3 m& Z; h; L( Z
*/
( A8 u/ Z% X$ U: {$ @1 hpublic DeptVo getOneDept(Integer deptId) {1 Q8 p! e9 \+ G6 `
    // 查询部门基础信息
* R! Q5 I1 \2 F% C5 \    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
2 }7 ~7 B+ ?" s% S. n8 D: B0 [    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
& k; s8 Y0 E2 ~( O- e    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
+ c) t3 p. {/ ^0 g/ f3 r0 y    return deptVo;
' m) B4 p1 Y) W% P" l}9 b/ h  h' U# A0 v  }
</code></pre>
1 J5 X9 V/ s: \; F<p>补充附加信息</p>
0 M# w$ K9 V6 t/ I" Z0 @<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
4 v7 ~' e* o+ g# ?  i* I9 I- _    // 根据部门deptId查询学生列表) a  d' _4 F* a& d& J9 [/ O- X, F
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());; s/ o: ]/ g# `) D3 j2 F8 f# _% V9 q
    List&lt;User&gt; users = userMapper.selectList(wrapper);
" [7 a; G0 _& d    deptVo.setUsers(users);( h4 ?; R; h, ^/ ^1 W' P9 ^2 A  J; `
}
9 \$ {7 G2 N. S( H7 s  f</code></pre>0 O; n7 u( ~& c4 {+ k% s2 q
<h5 id="2理论分析-3">2、理论分析</h5>+ f, K# w  e; Z+ L/ |( g' c! Q( X
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>9 S$ I: U1 ~! I8 K( n* U$ O7 L6 t
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>3 I6 k3 r3 L7 |* x0 Y" ]0 H
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>' C( u. ?1 ]3 V6 u: u$ s( X& L
<h5 id="1示例代码-4">1、示例代码</h5># n1 t2 @8 ^* p% V! X/ ^
<pre><code class="language-java">/**
& v4 k3 t" x& r$ G/ F; f8 L * 查询多个部门(其中一个部门有多个用户)& G6 ~+ e( f. V/ p& Y
*/
1 S8 O0 j) E' v3 i0 vpublic List&lt;DeptVo&gt; getDeptByList() {. P2 o) K! w0 |) k6 Z$ p
    // 按条件查询部门信息9 d0 ]6 T. z4 T* U  S* x1 L
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());- f: H, n: {- Q5 Q# Q
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
6 a4 [5 {  A  @4 l    if (deptVos.size() &gt; 0) {1 E5 P2 C; ?% q1 f1 q
        addUserInfo(deptVos);
# x! _# b9 e) g- m1 ~, m    }7 K; r$ J- m3 H. t1 w6 _' ^
    return deptVos;  L0 Z: D( L; u, [; ~
}+ u: T5 z! P: @* d( i; F2 ^) v
</code></pre>
7 Y9 F2 Z# @& v9 Y<p>补充附加信息</p>& j- k+ z: K& k) K; q1 e1 ?
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {: t0 Y9 a" g6 D1 l- q+ h
    // 准备deptId方便批量查询用户信息. ~5 x# ^/ w2 v& Q6 P
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
+ l" s# I" B$ }! A; @  f4 n5 j9 e    // 用批量deptId查询用户信息; {% l; k) u& m2 |( @; a
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
9 D5 P9 A% ^* |/ h  b, y8 x" P    // 重点:将用户按照deptId分组+ b( r) m0 p, M- g
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));9 l" c" l$ s) {( l! Z- \) ]7 i% L
    // 合并结果,构造Vo,添加集合列表
3 V$ a: I/ Q: I+ W' @" h  M+ d+ f# E( U    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
0 X. u9 b) Q( D  c" Q* [: w: C% ?0 ]}
4 g! P( t7 S  J9 V- n</code></pre>5 s$ p- S- D0 t/ O
<h5 id="2理论分析-4">2、理论分析</h5>- U; w. V6 K* E: B/ n
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>+ g, K) Z1 L1 i7 I8 s
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>2 o1 @6 x. s7 h% k# h+ A+ r5 e6 A- r
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>& z$ S1 r- R  i; b( o% @! o
<h5 id="1示例代码-5">1、示例代码</h5>: Y, p9 w" [8 T/ \8 s& m5 H
<pre><code class="language-java">/**
- P2 J, ^7 N7 F% }% W * 分页查询部门信息(其中一个部门有多个用户)8 M, L+ {$ z. R. |5 r, t) }9 v/ n
*/& ^6 w6 @* v: c- w+ K/ r% @% M' ]# s
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
, l. F+ m2 M8 L/ T/ @3 I) M    // 按条件查询部门信息
( }! M9 m1 f- p( ^! k2 Z9 g; [* d, J    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
7 {6 w  T1 f7 O7 M) i% O    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);9 f$ ]! e# U- y+ P  I
    if (deptVoPage.getRecords().size() &gt; 0) {! g! ?' \: t" r- @& p0 Y6 m
        addUserInfo(deptVoPage);# s7 }4 j, A1 F* _4 B
    }
* A% s- L; Z! P  M; O    return deptVoPage;
  l, u9 K4 Q. k" E}2 F, N0 }; ?* c/ T
</code></pre>- d$ B0 [3 C5 y% }
<p>查询补充信息</p>
  R6 t; `& a( G3 A6 d' D3 h<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
5 F! Z8 P, q: O$ u    // 准备deptId方便批量查询用户信息1 W3 G$ ]0 {2 C! E! w  g5 b
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
& p7 m8 n5 L5 C    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
# o# x; E5 v, V0 z# s2 e    // 用批量deptId查询用户信息1 [9 R, Y( ~+ o. }- |5 }# X
    List&lt;User&gt; users = userMapper.selectList(wrapper);
- `8 i! f# W& T. h7 `    // 重点:将用户按照deptId分组9 Z! h: }- L+ ~# V* z7 U! Z$ m
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));9 d4 u! l& P$ \, q& S- F
    // 合并结果,构造Vo,添加集合列表
( s2 {" j: c& _0 v+ t' f: T. M    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));9 Y2 h( |, ?( x  E
}
6 w# |* ]) W, r7 W# v0 K4 j</code></pre>% J2 A' ~( _, Z" k9 m$ a
<h5 id="2理论分析-5">2、理论分析</h5>
! q4 E: r7 C2 k, e: p4 d+ V* d<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
' q2 R* d$ P; |& k+ z<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
: g9 |7 \  \; D. \" n! I: p<h3 id="四多对多查询">四、多对多查询</h3>
( W* D) I7 s$ ?1 O5 H<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>4 E2 @8 Q5 L' z# R1 W' W6 y( S
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
" h& a7 D) S1 U+ R; o! b<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
  d% E' ~( x" S<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
9 M; D0 [: b2 B4 u<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
( z  Y: k# h# W1 P<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>4 ?" `( `6 V) k' d5 y  A6 e9 M
<h5 id="1示例代码-6">1、示例代码</h5>" D- i9 d7 \5 l  ~4 V
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {+ B) O# e. _! h+ K
    // 通过主键查询学生信息( \% r* _, U$ K4 r: ^
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);! d* C5 n0 J9 p/ S: Z. ^  z
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);! Q. f, [& x5 K, L- N, G
    // 查询匹配关系  H, z) H4 Z4 l
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);% |+ _/ `7 Z/ ~2 f; u# ^- o8 ]
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
' t% s4 j, S0 n    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {: F5 X- k# q! H2 Z* f% h# S
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
" N; r9 O# o9 j2 e: n4 _2 A7 x# X        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);+ o, N9 C" e) o3 p  V  Q- i
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
4 H& m& N' ?) F6 }: O  F8 e        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
, ^4 M4 |5 K. Z) t% F4 ^5 `        studentVo.setSubList(subBoList);) E* q" ^- f  M" g7 \
    }
& V- K3 s2 t* ^! h( ^. x6 o    return studentVo;. s1 u0 _- i" v. u/ U. G$ D7 M
}
$ x4 [1 @  X; y* P( R</code></pre>* W) Z# {, j& k7 }$ x/ O) p
<h5 id="2理论分析-6">2、理论分析</h5>
* V- d6 Y  n* u/ a+ c<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
- H, B6 G8 O- E6 v- L! `4 _( P% t<h4 id="二查询多条记录-2">(二)查询多条记录</h4># \" q! v* s  T( }7 ?, {/ k
<h5 id="1示例代码-7">1、示例代码</h5>, ~3 r6 E6 f* |
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
4 q+ \. J8 u. B8 o+ _    // 通过主键查询学生信息3 R+ v- {2 ]$ x4 n
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);: @- n( [8 r, x9 R6 N$ u$ E' y
    // 批量查询学生ID
: J8 D. B9 Q) f5 Y9 M    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
0 F4 P" I+ ~2 h$ L$ X: B    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);) y6 w' t; L3 {5 J7 A
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
: ~1 i+ F" t  P. ^/ ?# N    // 批量查询课程ID
7 o1 ?* ]8 a0 \0 O$ {. v' \& T    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());* x; }) n% S- ^/ B$ c0 {; L
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
. ]. z0 R. e; W, g; S$ e- i        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
  y9 F" F6 c. Y: P        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));, B: [9 s% n( V; t0 Z
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
% f0 n- |) H0 k- [4 [        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
0 w2 {8 @) h. B- a5 {* B        for (StudentVo studentVo : studentVoList) {
& Q& ~6 @1 r) c5 c" z            // 获取课程列表$ x6 y3 W8 j% a: H3 i
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
/ y" ?! Z  }' K- g0 w5 z: |            // 填充分数
% x  }9 W3 G% \% m$ z, l  \2 y& P            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
% U- O6 A! E; Z+ \/ T            studentVo.setSubList(list);% [/ l; c7 V; R5 K' k! y0 b# p. N
        }
0 U" p$ M& V, e    }
1 L- m! a9 V4 z1 z& j    return studentVoList;
, n% p6 o/ x: _, @9 |}2 K/ Q' A7 `. z. P! ?6 F2 |. A
</code></pre>
2 m  _- u8 `) X: r7 D5 a<h5 id="2理论分析-7">2、理论分析</h5>
2 f$ e( |" e! m1 y' y: M4 }" g3 u<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>- q* D1 U" U, @% U+ o, ~* G. K5 n
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4># A% V( J' v' G& ~) W  Q& `& @9 u
<h5 id="1示例代码-8">1、示例代码</h5>! N' B. W' c: T  S/ Z: a
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {  k, Z2 {) \+ \; q, `+ i
    // 通过主键查询学生信息& p) h0 Z& l. Q; X# N! ?
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);; C5 X# X& l* R5 e; G2 n4 N7 j  [
    // 批量查询学生ID
+ q! e  q- R7 x( Q( b3 v    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
2 S2 s% B9 Y/ d) X' M9 L! N    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);3 v; {' ?3 J6 P- t
    // 通过学生ID查询课程分数  ~  `$ I- a7 l
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);6 A  C  `0 b2 r/ D0 I' i1 z) y
    // 批量查询课程ID
3 {& B0 C7 Q) s* o    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
* Y; G. p% o  e; z/ ?; ^    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
- `) I' R8 R$ x* q. A3 H! X        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);0 p5 k0 T' U* C7 d6 |2 C6 d( o
        // 学生ID查询课程ID组$ ^; r+ A* g9 c# z4 ]
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));8 H/ `$ \& R1 I% W* g6 M
) Q" _, W- R5 A
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
  a3 I1 U3 E5 d5 s& \7 }: v/ s# A        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);' r4 K0 y* @* O$ Y
        for (StudentVo studentVo : studentVoPage.getRecords()) {7 H: a# d' D& S  ~+ w, Q
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
- A* J5 \& y/ g4 [; T; \            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
: E. c: W  i9 g9 [- ^5 ~( S            studentVo.setSubList(list);
7 x6 S+ n+ B* D& l        }
& y0 {  K4 i* x8 T- W    }4 _1 |9 c5 l+ c: k
    return studentVoPage;
: n' F& a* I$ |  F! L8 W}6 o' P- |& y% u8 K
</code></pre>
1 Z' ~+ d, X8 b4 y0 }1 P2 K<h5 id="2理论分析-8">2、理论分析</h5>
) r8 p8 j8 ?( U" g<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>5 k$ m* u% {  k" `* j9 \& ]3 Q
<h3 id="五总结与拓展">五、总结与拓展</h3>
- I' U& }7 m8 Z6 ~<h4 id="一总结">(一)总结</h4>
$ }6 Z2 p. g, @# w) O( N<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>/ T6 D2 m0 a7 j+ c
<ul>
$ a, L5 [  L/ U* d7 I<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
0 k! Y* J$ h# T  i1 n<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
; R' O2 L+ O- ?& x7 E) E<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
; E( Y* g" }, E2 ^( q/ N. _/ k</ul>4 T; m5 K6 h" N
<h4 id="二拓展">(二)拓展</h4>
4 L4 ~7 f% G/ I7 X3 t/ P7 E' M<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
0 n0 h6 A* D! y" v( B1 s/ t2 c7 `<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
+ z6 \1 V  D* J<ul>
7 C* d  J7 a  {8 Y9 u' _2 V<li>当数据量较大时,仍然具有稳定的查询效率</li>
; I+ H8 ~; ]! \' l& L</ul>
  F6 E; o/ `3 D) y1 _1 z<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>' d. Q8 r* _0 z* E1 H- k, q% ^$ L
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>1 Z' j$ g8 @% h; a
<ul>
, ^8 |% E( m1 V! p* D<li>与二级缓存配合使用进一步提高查询效率</li>& o2 `7 H! W! M( K% S3 w: [
</ul>
, I, S3 [8 J6 z0 s7 X" Y; }<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>; A& o3 X( i" ?0 E2 n( b/ {( I" m3 @
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>' l2 p( q( k( k, H  y

+ M$ `' M( C7 K+ v% H
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-1-5 14:43 , Processed in 0.071624 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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