飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8038

主题

8126

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-6 11:26 , Processed in 0.066000 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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