飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8059

主题

8147

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26507
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
6 X+ t/ w! K2 o% x& f1 B$ k& d% L: E
<h3 id="一序言">一、序言</h3>
! P0 r% r; u& h8 j5 q( v8 @" _<h4 id="一背景内容">(一)背景内容</h4>
( k8 Y. ?6 |! ]/ n& S8 z<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
% N: B! b/ i+ t  w" t# e4 e<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>6 a4 |( K! E( H) I) `
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>0 A" g3 ]  y3 s+ O5 G/ h
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
, N& Q& o% d/ z<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
4 d8 p7 R& J' t9 m<h4 id="二场景说明">(二)场景说明</h4>
( u& m$ @- ?+ @3 q. X1 {1 B1 `<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
2 Z6 C, \8 W; o, ?2 _<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >- V$ i0 D& h, I' |. E" |
<h4 id="三前期准备">(三)前期准备</h4>% w" F7 T. N; d' W5 ?
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>  E6 a$ `2 }2 h7 e1 N& E0 i8 p  Q5 _
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
/ I* E0 t0 G- ^! h. H) f7 S% V<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
! V( Y; p7 u7 U<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
9 j$ M9 W, ^* x2 A+ I2 J0 [<h3 id="二一对一查询">二、一对一查询</h3>
! O2 [" f& d2 x1 ]- V. B' O- P% d<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
2 v+ Y3 K' Z* B" ?<h4 id="一查询单条记录">(一)查询单条记录</h4>
- w/ ?' M, D$ x* }) g0 e<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
, I, R& Y% L+ N8 Z% }, ]<h5 id="1示例代码">1、示例代码</h5>% G. Y8 a" B. |" I2 J& v
<pre><code class="language-java">/**
7 h/ i3 L3 ^9 ]7 j  x * 查询单个学生信息(一个学生对应一个部门)4 f0 W. V% a/ u
*/
. h5 B* H9 h. K1 e' n) O7 s# j) J  k0 Npublic UserVo getOneUser(Integer userId) {
; T; e. ^/ R; U" f- n- t    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)7 h* D. u9 c# S; @
        .eq(User::getUserId, userId);
; c8 l3 u7 E- r( z) F3 ?    // 先查询用户信息
* n: ?% {7 l1 A* M    User user = userMapper.selectOne(wrapper);
0 J! V( c( I# P/ E9 N& m* s; d8 e    // 转化为Vo5 o: C+ s. U) s* V# S) L! v
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
- p2 [$ x1 {# x/ u" a0 \6 |    // 从其它表查询信息再封装到Vo4 G' C1 O/ l0 W8 j) Z0 m
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);% c1 r2 E7 W  c5 n& {  K& o
    return userVo;4 z+ T  {7 _% c& `( A- m
}
  J/ G3 m' p" n( k" s6 F1 W$ u  `! g  v</code></pre>0 H# N0 U) v7 P+ J! f/ E, n
<p>附属表信息补充</p>
* o1 Z3 B9 }+ {" V% g, V% m. ^<pre><code class="language-java">/**
9 w9 B2 L4 _* X * 补充部门名称信息
1 F) s0 T) T3 {- D! T7 t */
( \& ]9 j; Z+ P  V0 l6 \  kprivate void addDetpNameInfo(UserVo userVo) {: F! \/ V) ~( R2 ~  {( D! t
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
# c  K3 W3 _  J! @  h' j        .eq(Dept::getDeptId, userVo.getDeptId());1 D! h6 A8 P8 m5 n4 A9 }
    Dept dept = deptMapper.selectOne(wrapper);& |( h$ u& r3 c; z+ P4 d
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
" v  n; ~4 [0 A4 L$ R4 e}; S  z; H2 X  f$ }
</code></pre>
! |0 V8 f7 g& N* x3 {. y<h5 id="2理论分析">2、理论分析</h5>
: D* W0 V$ w5 c+ u" M<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>* l+ r7 n  Q* I! {
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
3 H) Z4 l3 f; a1 Y: S' L# L<h4 id="二查询多条记录">(二)查询多条记录</h4>
1 k  `- [6 H1 s0 u% j( k6 E<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
  ?4 w9 O  z& O; P( V. k<h5 id="1示例代码-1">1、示例代码</h5>
4 |7 n) n$ b8 _: L4 b<pre><code class="language-java">/**% @" F4 h, h3 H) C6 P+ ?( a/ B$ v
* 批量查询学生信息(一个学生对应一个部门)7 S2 v: J4 t& x
*/
6 ~, A4 w! Q7 x1 s$ Z' @public List&lt;UserVo&gt; getUserByList() {8 r( f! _9 v" _. V7 |( s8 j8 X
    // 先查询用户信息(表现形式为列表)
. a) J# s& D' i  o4 s" B    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
' Z; c6 D( s# _6 P; K# D    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());2 r" Z* w- L. m8 ?
    // 此步骤可以有多个
8 H* N( a. B# b8 {( f    addDeptNameInfo(userVos);
; T0 r" f, i- J  W8 u    return userVos;
; q0 c+ i. E  Q+ n+ J0 |}
" G( q& a& D: j  K$ o, H! I</code></pre>
& s7 M- `; e# G1 D+ i0 ]<p>附属信息补充</p>& U' F6 n* q, t& Z, M
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {; l5 T9 |0 N' O( L% W! u
    // 提取用户userId,方便批量查询
9 |9 Y2 @6 E2 p& f    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());$ b+ J8 H- c3 w6 O9 j; h! d5 Y
    // 根据deptId查询deptName(查询前,先做非空判断), U* Z# I9 _1 y) k3 W! K3 I
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
- }! p! D0 }/ c$ C5 P$ r0 }' Z    // 构造映射关系,方便匹配deptId与deptName
  P$ [0 ]3 z+ z5 L% J    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
/ i  z% n4 D' N0 S8 O    // 封装Vo,并添加到集合中(关键内容)
5 G, ?4 T( b5 ~6 X. i    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));8 |( q6 i3 B% z- S/ D4 `
}
, N- N4 q6 R+ t( _$ E1 w. a</code></pre>$ V( o: E$ H# X% F% D1 x( F
<h5 id="2理论分析-1">2、理论分析</h5>
) }. A+ b+ V; Z7 o- u7 |% V<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>% N; D8 D: Z. U" F1 s
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>& o3 f8 I: S6 o% H7 u
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>1 N* m4 S6 z8 U4 X! \& G0 Q3 F! H
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>% L1 H0 z  a5 U. O% d
<h5 id="1示例代码-2">1、示例代码</h5>
4 l. H5 W* P% f+ I4 [  y9 B& k<pre><code class="language-java">/**/ F" o  J6 ?) o
* 分页查询学生信息(一个学生对应一个部门)6 U: r( E" F5 H9 ~  g5 u. c
*/' C' a$ u7 g' e3 O& X
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
7 t! S% b  L% n- s; Y    // 先查询用户信息
& k3 ?2 \  ^( Z6 f# b    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());& z2 Q1 v$ v0 i3 x- M
    // 初始化Vo
* K! x/ f- Y0 S4 T! }7 c8 L    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);/ ?6 X4 H0 I3 i0 z- u( a2 P" N
    if (userVoPage.getRecords().size() &gt; 0) {  b' h& \1 f) U
        addDeptNameInfo(userVoPage);
/ Q! H9 K: g0 G    }  e8 ^$ O) p% j/ t5 H1 R
    return userVoPage;8 g  e7 G, A% T8 L
}
2 `1 f2 v5 ]- v: q7 p8 g: X, }</code></pre>
4 r: ?, J$ [2 D$ _<p>查询补充信息</p>$ @( I) L" L4 _
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {, }) D. K( u& i+ b6 B9 @# c* h
    // 提取用户userId,方便批量查询: h1 E4 j2 V( A1 k0 |4 s0 a& P
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());+ s3 @2 Y0 q4 J- U' C
    // 根据deptId查询deptName! ~+ d0 ?; ~  L
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));2 _' X7 C9 x1 I/ T
    // 构造映射关系,方便匹配deptId与deptName, p+ E1 L) q5 o. `1 K' W  W# q
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));5 a+ U+ E( `9 J7 p( D
    // 将查询补充的信息添加到Vo中
% z0 Q5 H: }0 E4 q) d    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
8 |$ E) Y1 h2 C$ R8 Y7 ~}& g' l# q8 [, D4 v/ ?& u
</code></pre>1 Q. N+ [" e. P7 B) ~7 q! O
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
& T9 X% |: `, c% F9 O) M, N: q<h5 id="2理论分析-2">2、理论分析</h5>
- V. a# U* y. s<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>$ n0 r' z, B+ l
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p># N. }6 x- Y2 \& x: H. _2 ]
<h3 id="三一对多查询">三、一对多查询</h3>
4 V! r" U. R5 E" S' X; K<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>8 C9 U5 J2 C! a$ ?: i& p
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
; I; i3 m! w. j  V# [/ R<h5 id="1示例代码-3">1、示例代码</h5>" f5 M6 A( V1 v) ~1 O
<pre><code class="language-java">/**
) r3 E1 p: X4 E2 x/ ^  e9 @# |& ~ * 查询单个部门(其中一个部门有多个用户)
7 I. R- E2 Z" W, ?" Q */
& D! p- E" A0 q2 u8 d8 tpublic DeptVo getOneDept(Integer deptId) {. S& a  @9 H1 `
    // 查询部门基础信息. V& ]- U( r5 s/ E
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);! ^  I+ H7 W! F) d1 R. H$ e) N4 `
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
# r% e3 x' l. k" P, l    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);4 ?, d  p% F& \$ }
    return deptVo;2 _9 H; C1 H. e; B% ]2 G
}
$ n' W) d; d1 G* k) f% p</code></pre>
7 ^8 V2 f6 z' E2 a) ?<p>补充附加信息</p>
- g: Y- i$ ~& t; I- Y. |6 Y& o* m<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
6 b; R1 U7 `2 h' z+ }    // 根据部门deptId查询学生列表, l# N% C+ G( X& T' t
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());) y- s* o# m% `$ H* Q7 C
    List&lt;User&gt; users = userMapper.selectList(wrapper);
9 i- H7 p8 Z: ?: E    deptVo.setUsers(users);* ~' n8 `- I2 ~) X% F  {/ V" f
}
2 z( ^) g5 m+ @</code></pre>0 g1 C* ]/ d: `" x, I9 n
<h5 id="2理论分析-3">2、理论分析</h5>
" |) T- Y. y+ n. D, B<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>- o# y& l& ^, H) p+ u7 P' `# c
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>8 F. V! _. Q% e% B1 g! o$ j
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>, ]3 b. E) E$ w0 v- X$ j
<h5 id="1示例代码-4">1、示例代码</h5>. I- d  F5 n2 d) C5 W; D
<pre><code class="language-java">/**
, G# W$ o; n2 j2 K * 查询多个部门(其中一个部门有多个用户): y% l9 @# {( |
*/
1 c, |0 ^' f) Q: n0 ]public List&lt;DeptVo&gt; getDeptByList() {
2 y* ?8 {) r. ?0 K9 ?    // 按条件查询部门信息
, I  N  Y. [3 }# J: p! D2 ^    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
. J) ^4 K! A8 r; d. G    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());& H* A5 A3 Y. i- Z& g+ R/ f2 c2 \4 Z
    if (deptVos.size() &gt; 0) {/ E/ Q2 J0 x8 J7 ]! v- _5 ?, P0 l0 y, f
        addUserInfo(deptVos);
( ?# `- ]! Z: U' B7 b    }+ I& @1 g8 |/ \
    return deptVos;
) o% t- |6 f( R: u}
' f, p* K  n  _- Q7 K; z</code></pre>4 |. Y" x' l5 X! Q+ g" B
<p>补充附加信息</p>
( }" i+ j7 C+ j3 {0 h<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
; @5 H* u$ A/ _    // 准备deptId方便批量查询用户信息
  K" U, ?; R2 x; L4 F( ~8 k6 ]    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());# I0 h* T. o- k& Z, V* m
    // 用批量deptId查询用户信息
, D" V$ [# ]# ]  {/ x; K    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
# e; H- r* I6 a; ?/ L    // 重点:将用户按照deptId分组  X9 R0 G# J2 b5 n: E7 y5 h
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));3 }, E6 x- E! v" _# s
    // 合并结果,构造Vo,添加集合列表
6 b- g8 q0 A0 q* O. I    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
! L( O" j. n8 ~6 D' h9 N}
, g6 O# @" J( j</code></pre>
0 @  Z! C5 h1 h8 j' j<h5 id="2理论分析-4">2、理论分析</h5>$ G) I9 A# C+ t3 ]( H
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
: ]8 h% K; g, w2 H: i1 P3 t8 U<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>$ h) P4 J2 [# j2 h
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>) I; `* k! Y! g% v" g
<h5 id="1示例代码-5">1、示例代码</h5>
$ z' M& \2 @- [5 G<pre><code class="language-java">/**
9 [! J. i0 V  O: y8 N * 分页查询部门信息(其中一个部门有多个用户)
  [" [2 Z6 J- k */
, k' t! R$ u: vpublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {, o* N, X. x8 y6 r' G) S6 N
    // 按条件查询部门信息
" }8 V- }% S& ~( f- T2 ?    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());5 V$ B3 q5 A+ |& T
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
- Y- y& X$ G9 H1 y. f! d' |    if (deptVoPage.getRecords().size() &gt; 0) {7 ^- Y- |$ K& K: g$ C3 ~# j
        addUserInfo(deptVoPage);: u6 [8 e2 t! G5 d* V: U. A
    }  h! t8 D$ \% k7 T4 W
    return deptVoPage;
. U3 [. B6 Z/ D! r3 i3 ?7 {  T}
' g8 |+ z5 V- W/ X0 D</code></pre>
1 ^+ _; t, D2 B& I1 E5 K<p>查询补充信息</p>
+ X! N# b/ x& }0 B% q$ [<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {; c* U$ Z# d* g; V" \! L
    // 准备deptId方便批量查询用户信息$ p" v$ Y4 R" D5 i) _6 s8 Q
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
# x+ E6 M  E$ ?) L    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);' J) w! O) W; B! T2 G5 o4 a/ |. M
    // 用批量deptId查询用户信息
% h4 p2 E0 _" h8 r9 C* w. d% b1 _    List&lt;User&gt; users = userMapper.selectList(wrapper);" K% Z, `3 U! [; M9 h
    // 重点:将用户按照deptId分组
5 S! R; {0 a' [; m    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));0 E1 O( z1 L2 F' B! C% L: b
    // 合并结果,构造Vo,添加集合列表
% J- }: x  C' a1 N. C    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));) U8 p% s( y: V1 _) T
}
1 {- a" y. K8 p</code></pre>
- z8 |( t' B  c# E" A<h5 id="2理论分析-5">2、理论分析</h5>- O2 X; x/ Q& U4 z. s" l
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>( a! |; \4 o! J# o
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>4 s# A% r. F5 Q0 a$ O6 ]% r
<h3 id="四多对多查询">四、多对多查询</h3>
. D- n9 }1 ^/ R. ~) y6 `2 c<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
# U2 x2 H- H3 Y! T  S3 B<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
1 i7 p* C1 B5 B<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p># }( Y- H4 f. \) V/ c
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >4 F+ d' P3 b! q* J+ K+ d
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>7 X9 L- W, y, q0 n/ v& \6 t; l! y" T
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
" l! `  J3 a! n9 S6 X; }<h5 id="1示例代码-6">1、示例代码</h5>" ?; q4 M: N. U& ]1 ?7 ~
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
0 t2 E9 h  j0 w3 P9 g2 b& N& @    // 通过主键查询学生信息
& T3 S6 h$ H- I* @( f0 G/ E    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);3 T/ Q9 c& f" T# d" J) Q
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
2 B4 |* r* G: L7 o9 K    // 查询匹配关系+ g5 V! \" D9 M: U) `* I
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
4 t2 Q' C/ O; x    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());9 ^. }' b$ K2 Z3 B( O( g
    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
9 C. @" o% z. e& |8 I        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
9 i& g0 d( H! T: }        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);+ I8 q7 H- `* b- L' T3 B
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);0 I) `" o( S4 a0 J4 X& ~
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));+ D' K# F9 z3 a
        studentVo.setSubList(subBoList);3 Q9 F3 D/ M! ]2 d3 U. w# x
    }3 k- \; E0 K/ N8 w
    return studentVo;. I. q" v4 t& `& I
}% z$ I$ S- k! K
</code></pre>+ |8 U2 D, p1 o" [
<h5 id="2理论分析-6">2、理论分析</h5>
5 K7 Y# D+ j( F, K5 L) ~<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>/ R% \0 R; ]% u& n7 U
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
9 E$ V9 w+ C. R7 b& k2 F<h5 id="1示例代码-7">1、示例代码</h5>
" A$ [8 [. M& a' ?: c& t<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {- N5 N( ~& m, ]3 {, E  _
    // 通过主键查询学生信息0 c9 ?2 ~3 Y1 w4 j% v2 P6 U. `
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
( q9 X' f8 f, J    // 批量查询学生ID$ r* f  W- q( C' [9 m2 a
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
8 e7 b% p2 D2 ]- M0 N3 }    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
: m  [. k2 K0 M    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);) Z& T! d" b/ T# R$ |
    // 批量查询课程ID5 U4 _7 X% E( P0 K+ o! s
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
5 `$ Y5 I9 p& L& W/ j    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {5 f& l3 k- ?* O+ H/ P
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
  N: M( u0 P1 K8 S# g9 `9 p        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));! h5 @+ k# r! I2 G
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);  V& b% L, t0 G  {* D; g' i6 A
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));, w( {; P4 l2 z5 u* X! }. M% R
        for (StudentVo studentVo : studentVoList) {& r. V% {$ q+ @- q
            // 获取课程列表/ E7 K" O7 }% e# j% i! t5 v
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));  w0 C* I/ X9 `- A. F
            // 填充分数
+ w& F$ Q4 h& [( T: r4 `' N8 D, P            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
$ d. i9 o" K1 W5 h' i+ B$ ^( a/ U            studentVo.setSubList(list);
3 K1 n, `- K) |. x9 s        }+ S+ u4 ?+ H, h6 C1 N1 E9 n
    }% e! _  p  n) U! u
    return studentVoList;6 {* u6 |4 P* \1 u! O7 m- f
}
! }& N" Z4 ~0 _# n</code></pre>
0 h6 K% i) B% E" T6 I<h5 id="2理论分析-7">2、理论分析</h5>2 ^5 e! b. w* H; q
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
: s5 ^2 |% X8 ?* q<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>: I; t) e1 ~& k. t1 e, u- ~
<h5 id="1示例代码-8">1、示例代码</h5>
2 X2 T( ?7 @8 @<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
$ M, n3 g# f0 T4 j6 L8 t$ p- i    // 通过主键查询学生信息
  G$ Z% K2 f; R: r3 r; d' Y) l    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);" F% R. n/ `) j: H# ~- t
    // 批量查询学生ID
, s2 M+ E& j7 W; p- r7 I" m    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
: m$ A- X# V5 u3 B" @( E) ~( ^/ U    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
8 e1 I7 T2 Q8 f% D    // 通过学生ID查询课程分数  i: @. I5 s" e/ ?& r
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
$ _# Q5 k5 \6 x+ }. A    // 批量查询课程ID6 F% n+ J) h- a( A+ |) j. D
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
3 P! a; _1 o. j    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
0 k4 S- q$ }$ T8 j        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
8 e& p7 G4 f4 K/ h/ B2 o        // 学生ID查询课程ID组
) ~* r+ a* V  ^$ z+ d& H2 x4 w        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));# J( I! C4 n# M

5 ?: Z: t& t) k! s* T6 ~3 Y1 m        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
" x; ^  U9 G+ J% C        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);: y. p* y8 O! I& N6 A
        for (StudentVo studentVo : studentVoPage.getRecords()) {
( A) q# M1 G5 w2 v0 [( V: T            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));, Z- |. H# m* u% Q
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
- R. p- Q# N9 v+ @; b. C$ @            studentVo.setSubList(list);
5 C4 f( f, _2 L& \+ |        }( U+ y5 B* {/ V. L1 n! k7 R" o
    }
  X: p/ ^0 k6 P; ~  d- e    return studentVoPage;
% p1 E. y7 v. G$ E; t}9 Y( u0 ^: ~" \8 M: C+ l
</code></pre>. {% ~2 \  s  q/ ]' f3 M% A# `
<h5 id="2理论分析-8">2、理论分析</h5>
. j1 t3 N0 N8 U; k, G<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
; X# P' U# z6 F, h, k( s; _1 g  [1 \<h3 id="五总结与拓展">五、总结与拓展</h3>
) b( ~  p+ |% o- q0 J: u8 w<h4 id="一总结">(一)总结</h4>
. _. B+ Y( M# |) r. r; O& L<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>, ]/ d. U+ Y  Z: Q( m* a
<ul>; V+ j5 k2 S  `9 Y" N
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
  E  _3 x' R8 P# q7 D8 N7 Z0 f<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
6 {8 g8 y  Z* O/ g6 ~. R<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
  r" i( \5 R( I& }! z</ul>
1 |6 [7 X" N5 ]<h4 id="二拓展">(二)拓展</h4>
& k% g+ w: V! g" s6 q$ X, G<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>2 h. s; l3 |6 V) m- d( K5 Q0 `
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>/ i$ ~2 ]0 q% r8 a- |
<ul>
: v! o2 @* V3 V# y) b8 k  t* Y<li>当数据量较大时,仍然具有稳定的查询效率</li>
- i& P# ]3 @$ P6 z% N( o</ul>. T$ h" i' c8 X
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
' |5 o, @) y% x9 F1 t<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
6 ]1 N4 t2 S. d9 J$ A<ul>
% }  k! a! e  m; x<li>与二级缓存配合使用进一步提高查询效率</li>) `$ V, V; u3 m0 W- s) w
</ul>
# O- B( I; Q, [1 ]  E* w8 L4 G: j<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>" b' |( E, k% l
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
5 W/ y% r& O, `0 W
4 ]/ q6 d! c1 i0 d8 i8 _
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-14 12:13 , Processed in 0.073117 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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