飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8240

主题

8328

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

, O* W) P) n5 p. k3 v' P* H
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-1-13 08:20 , Processed in 0.065338 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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