飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8034

主题

8122

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-5 01:50 , Processed in 0.071064 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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