飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8034

主题

8122

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26432
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
4 N7 D7 v% o, g9 E: k5 F2 G
<h3 id="一序言">一、序言</h3>) a/ O- f- |3 J; E4 ?. W
<h4 id="一背景内容">(一)背景内容</h4>! {) V9 s. T: Z2 X
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>& ?% O& H* ?! i7 s& u
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>% D1 ~( f4 O/ |
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
9 ^" Q- W0 \4 k& L( Q+ H* ]<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
6 g5 {' N% p3 E* V- y+ A9 b$ O<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
  n3 {- @+ Y; k# D<h4 id="二场景说明">(二)场景说明</h4>
" p2 |  Z0 ?! \0 ~<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>5 H) o& o9 |; x
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >1 g0 R- Y3 X) ^9 \4 e7 J
<h4 id="三前期准备">(三)前期准备</h4>1 F+ z9 a2 r( _4 {
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p># M# B" }4 K3 K7 w% q- K: H
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >1 u4 n5 |' J7 y. _, x# r
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
8 e; r* H7 x, a) _$ U, @: B<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>/ [) ?$ H! S/ O
<h3 id="二一对一查询">二、一对一查询</h3>
4 {& E# A. Y$ Y1 T" W8 V<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>4 h2 B4 m( t; M4 x" {2 G
<h4 id="一查询单条记录">(一)查询单条记录</h4>
4 w$ H/ f9 c( ~2 A3 d0 I<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>4 V5 b$ k! s+ q( U+ m( N4 ?* O. c; n
<h5 id="1示例代码">1、示例代码</h5>
+ {4 ~# O. j; ~  q<pre><code class="language-java">/**! G  b) h9 P! A/ y  {" p
* 查询单个学生信息(一个学生对应一个部门)
0 e* M2 Y1 O8 d. B$ V4 _ */
$ Z. B" h5 J8 y" m# `0 [1 e9 h3 w9 m% mpublic UserVo getOneUser(Integer userId) {
8 b1 y% m# [4 a" R6 t    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
# i) ?7 ]7 @% O# C! i1 `        .eq(User::getUserId, userId);$ I6 h3 V' c; d7 C6 N. d1 ?, Q
    // 先查询用户信息' j2 x. j( E* D- a" `& P" f
    User user = userMapper.selectOne(wrapper);
6 A% E) z! s8 W; _9 u$ d3 O% w    // 转化为Vo) H9 y7 x4 i& }. D; Z: w/ m
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
8 ^, O( j- a9 n! _& l    // 从其它表查询信息再封装到Vo
7 o: L# d# `3 l5 B    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
, {+ \# u& u; b+ Y5 K( a/ j7 @+ @    return userVo;  i8 X- [: i+ n% h( s  R
}- y/ H2 o) t+ W( n. ~
</code></pre>
) {# z, A! I  d3 Z& c<p>附属表信息补充</p>
' y6 Z5 T  Y, M: |+ r* k<pre><code class="language-java">/**4 k* G) Q/ t. B5 }) H
* 补充部门名称信息0 j) i, j: Z3 X  X5 z, r
*/& n. f, I! F! K7 A/ N- V
private void addDetpNameInfo(UserVo userVo) {7 z- q/ s8 N5 z1 W- v# z
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
5 Z- }% {' {9 n: t& E6 |$ j        .eq(Dept::getDeptId, userVo.getDeptId());( K9 s( h  f2 a& y! ^
    Dept dept = deptMapper.selectOne(wrapper);
7 q' y4 k7 R/ m& P! P, A    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));3 s/ S/ l- W5 N9 A
}0 f3 ~$ x$ f3 _0 P
</code></pre>
) r; I6 k7 c1 O  j- V<h5 id="2理论分析">2、理论分析</h5>* U: I& d2 L2 b/ j1 n8 B. Y, D
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>  K. x: e% B" r, l
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
& d; q" `; d9 M' I( f<h4 id="二查询多条记录">(二)查询多条记录</h4>. P' u! B9 ]( |
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>8 M9 M5 M, A" B
<h5 id="1示例代码-1">1、示例代码</h5>
# r5 q2 X, V4 y/ ]<pre><code class="language-java">/**6 a0 X4 Z" E: X0 S
* 批量查询学生信息(一个学生对应一个部门)
5 f# A$ U$ {" s9 p$ ^6 P# A */
0 G: n% p  ~. N3 V" r: gpublic List&lt;UserVo&gt; getUserByList() {' j1 @0 \9 f: H
    // 先查询用户信息(表现形式为列表)3 G; b7 M" Q0 @: s( m1 h/ |
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
6 G* W7 \1 Q. [! ]9 ?  u. j  K    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());) D7 E8 C4 \8 T5 l% ]0 b, Z
    // 此步骤可以有多个# ]! x( i5 K5 `0 I7 Q
    addDeptNameInfo(userVos);( F6 G9 P2 `. `) S3 X
    return userVos;; K* b5 m* U/ l/ c
}( Q0 p6 a9 U- q4 d: N5 G9 B
</code></pre>% a+ ?. F3 g: {% v
<p>附属信息补充</p>7 A  s* ^" I9 H. h
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {7 y- F1 [. s/ w8 M9 M0 A
    // 提取用户userId,方便批量查询
0 b/ F; `# ]( `, x8 w    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());( w: D# e! \! ?, \$ @, H
    // 根据deptId查询deptName(查询前,先做非空判断)6 {1 |7 S9 g3 n) v7 i; |4 B
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
) j2 ]+ h$ v# M: G; x0 w    // 构造映射关系,方便匹配deptId与deptName
) R$ R. Q; j5 e+ z* d1 W    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
7 I+ k2 z% M1 o2 L; ~* _0 U: D- n    // 封装Vo,并添加到集合中(关键内容)5 ?; z4 ?: A$ s; L
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
3 @; |" l. f& c' p6 `& E& ^}$ \( D! W2 D6 K2 Y
</code></pre>
5 l; Z1 B  [; d$ T( F2 n& k9 R<h5 id="2理论分析-1">2、理论分析</h5>' V+ g! s' E- G- M2 `0 ^, a& o
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>" V8 Y9 R" j" i3 u
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
7 D- J" e- \# \5 h" O) g7 D<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
. p. R( o) {1 N<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>6 w' t8 q4 O4 n0 W/ e
<h5 id="1示例代码-2">1、示例代码</h5>
/ c5 B5 n8 K4 m7 Q9 T& y6 R" F5 d<pre><code class="language-java">/**( F0 H. J& H" Z! s' A
* 分页查询学生信息(一个学生对应一个部门)1 B1 j5 w! h7 z$ S& v( X- p
*/
3 J3 h) Y  n* ]! i. Z  ]; i# i0 [public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
8 h: y! r+ ~5 ^- @) v. y/ m    // 先查询用户信息
- b$ f) Q' I  v$ a' X' q    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
7 }  J8 g2 F, z3 K( N* y    // 初始化Vo
* ~- @: X6 ^0 Y6 s1 r: j9 r' s9 a    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);" Y: |4 r" X; d! s5 W
    if (userVoPage.getRecords().size() &gt; 0) {1 ^  W  y; l/ n1 V9 l/ K% p( w
        addDeptNameInfo(userVoPage);/ d+ G+ z* R' k, R
    }
( M" y' T- Z$ r    return userVoPage;
* F7 ?5 G6 o- w6 Q" ~7 U}
0 _' R/ \* N3 k/ v</code></pre>) I% m0 x8 z$ N5 ~" j4 f
<p>查询补充信息</p>1 s8 H' t% u9 v! c& v6 b
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {8 V$ [) _/ |) `5 k/ \
    // 提取用户userId,方便批量查询
7 z* ^' j9 o4 ^8 S0 j    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());* `9 W1 x" i: s
    // 根据deptId查询deptName3 E% k( B. u% b6 ?8 f
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));. @5 J% `. c) h0 g. j
    // 构造映射关系,方便匹配deptId与deptName! k% K4 v8 n0 {: j. h5 {) V6 R7 P
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));5 t/ U/ c3 s; K% R5 c. {
    // 将查询补充的信息添加到Vo中
  u3 [+ }4 l1 x' I    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));; o- E. h1 o% b0 M
}9 t+ h, O, b, M
</code></pre>) q) i- u9 _4 |  i5 ^4 S
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>* n4 W/ [9 i7 R, h
<h5 id="2理论分析-2">2、理论分析</h5>! `  R* m" s) P8 p  t
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>6 C5 l) a7 E- ?7 }2 T* i5 k7 B
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>% f5 B) e- W. n5 q: B
<h3 id="三一对多查询">三、一对多查询</h3>
! ^; t4 e- q5 Y  j4 q# E<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>- e1 y& n- J0 q+ A3 {
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>( [% T; P7 w# T4 m
<h5 id="1示例代码-3">1、示例代码</h5>& Q- X& ^( o+ B6 {
<pre><code class="language-java">/**
" ?% t! R( t$ m) X6 O * 查询单个部门(其中一个部门有多个用户)
1 j' ^. c" I/ z' Z+ ] */# F/ k% L# E1 _- W9 \+ ?
public DeptVo getOneDept(Integer deptId) {/ ^4 m- P' \! Y; ]7 \: s
    // 查询部门基础信息0 F6 b5 l6 w% P  ]
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);1 U, w, w( ~) T! ^/ c+ w+ M; A
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
* W+ j% a" \6 F; y$ C, h    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);# J" S4 T; H9 T8 c* h* J
    return deptVo;* ?1 j4 k2 ]! F' a- [
}
6 t! C+ Q: B9 I  A. ?</code></pre>" B! }( T" A+ u/ f5 T
<p>补充附加信息</p>3 B6 Z& I+ l. B3 ]; ^4 `- I
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {. B' E$ [  l3 M" |
    // 根据部门deptId查询学生列表
* V" n% q  I/ Q  M, V$ ]1 J$ @! y    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
0 v. q, i2 j: J0 t3 G; d    List&lt;User&gt; users = userMapper.selectList(wrapper);2 x" P1 ]+ p  u! ?
    deptVo.setUsers(users);( O* [" t) G" c+ H
}
8 b9 a7 O$ Z6 y</code></pre>8 o0 r  G  l1 @5 B
<h5 id="2理论分析-3">2、理论分析</h5>
1 x+ u' w5 c/ U6 l% x<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
! z- C. ~: N1 T/ p<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>% x- y+ n1 ~' x! Y% B* e; H
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>9 n4 [" `4 G6 Z  y$ i+ j. w0 F
<h5 id="1示例代码-4">1、示例代码</h5>
+ t. W4 i* H8 g) G. s1 d! ?' ^<pre><code class="language-java">/**
* |8 [- @  D% ]8 w * 查询多个部门(其中一个部门有多个用户); Q  N: H! _$ P% a0 Z
*/
2 W, ]  e. R, O  ^9 C9 E* `public List&lt;DeptVo&gt; getDeptByList() {
: z0 C1 c! p) U: @" I- V    // 按条件查询部门信息7 V% C+ Y" n1 q  {
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());6 e; S9 h) S2 @/ n8 f$ j5 x; s
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
# x" o% U# @( e    if (deptVos.size() &gt; 0) {
% @3 S: Z, F/ q" L( I        addUserInfo(deptVos);, o7 z/ ~- L! r) {! o1 v7 h
    }, E" H  V; p9 B7 R/ h
    return deptVos;
6 f0 e! _% c  K9 X. ~9 E}
" i, W1 }5 j: O6 r" k: O0 C; Z6 l</code></pre>8 g* ~" z0 [& {4 }" J$ Z/ y0 c
<p>补充附加信息</p>
6 |0 U! R3 x* I0 C: H2 K- v( Z: K<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
. N: E( q6 h1 ^" |' c    // 准备deptId方便批量查询用户信息4 g: F6 R& b* o. j, }
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
5 d- ]! L' l5 F) {    // 用批量deptId查询用户信息
* b& ~0 q" Z, q! H3 d6 _; N    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));$ c" H4 o, V) C+ Z+ L
    // 重点:将用户按照deptId分组
% h7 u8 B2 D& \: G    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));9 V9 w$ F( K5 g: f4 G6 }0 B' A" M  W
    // 合并结果,构造Vo,添加集合列表+ O0 _- u4 O, e& ], D( l4 O$ R
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));  y' g3 x. V* b& t
}* C5 o+ }6 n7 q" `
</code></pre>
( w, Z' r& l7 V/ M. D6 t; t1 J% W<h5 id="2理论分析-4">2、理论分析</h5>$ p% N8 U3 |9 e- \+ c
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
: f6 @$ Q2 m1 x, Q# _<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
0 S0 \# d3 `' O( S  V% p$ E<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>5 D% H8 X& a; T; F) L6 _- A1 s' G( ^) v
<h5 id="1示例代码-5">1、示例代码</h5>: m# M* X! _: P: A& T  t* |) @
<pre><code class="language-java">/**
: _; i! _% h9 N, t2 F2 L) g9 J * 分页查询部门信息(其中一个部门有多个用户)
  o+ m3 r- q& m# k */, `( s+ U8 W8 {  L2 k' x3 T6 x
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {4 V) k! O+ e. u! L- s+ s& A6 ~
    // 按条件查询部门信息
7 M* r) j( o/ ~2 ^  T8 ^0 b    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());" q! \5 s6 G% I2 q4 u9 ^% b
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
6 o: R$ D# X! {    if (deptVoPage.getRecords().size() &gt; 0) {
/ f, ]- M) F) [0 X6 E        addUserInfo(deptVoPage);& _. W  x$ }0 |% J
    }& l0 N3 p( M: y. `
    return deptVoPage;
, J( ?6 h5 B) p7 k}
& S& [/ ^, S9 C3 V+ |* K: X</code></pre>( ^' G, ]5 T5 A+ k* O
<p>查询补充信息</p>
1 i  B5 ~3 h8 G<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
2 f% @* m1 q$ v$ v$ Y  h$ W% t    // 准备deptId方便批量查询用户信息4 q7 o& e1 M$ ~$ [; ^1 L
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());  n- B8 N7 `' M1 b
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
9 \0 ]% R6 _) T$ W* j- I2 ]    // 用批量deptId查询用户信息
# S2 `4 Y' h' u) k% V" |    List&lt;User&gt; users = userMapper.selectList(wrapper);
4 Y, u. m0 G% I/ n( D; G    // 重点:将用户按照deptId分组
! L9 ~: t. r  `) W9 W- y' j    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
: o- ^2 a  q. D) {3 q1 F! C9 n: z    // 合并结果,构造Vo,添加集合列表( T' v; b# E% u6 `/ u* g
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
' l$ c& I( C; i; f8 x}9 s  j4 l3 s5 Z8 E
</code></pre>
9 [* T0 Y' \, W4 Q: a% I3 M5 b) S<h5 id="2理论分析-5">2、理论分析</h5>
4 |* z& z+ Z3 ^- r, L5 ~$ U<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>5 V& e: h5 [3 j4 @+ V' r& U' l
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
9 n+ ^5 U9 \* p0 L<h3 id="四多对多查询">四、多对多查询</h3>
7 A* o& Z0 L/ }6 N6 b, T% S<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>" ^/ I  T; z4 N/ _1 r0 A
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>+ u5 D; Y- `  I' F
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>9 J/ N- G; E2 w) @  G9 c0 K
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >& Z6 g; }0 g- ?% Y. ^% u3 w
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>: |- c9 i! u, B+ ]
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>$ C1 }! ?4 V6 }9 D$ @; b
<h5 id="1示例代码-6">1、示例代码</h5>
& s  C4 e6 ?  g& I- D6 Z; N<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {  U4 f4 F2 l* e
    // 通过主键查询学生信息9 n0 ]! V* s8 T' ~$ W/ M
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
1 _6 Y; J- u. s    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
& _0 R! T' v" D! k$ [  l    // 查询匹配关系
2 }- m! q0 o; P7 t3 A" X! {    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
  b$ y; z! S9 p    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
7 Q' q+ L' P7 l( j3 z    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {! H- ]5 h2 U, L
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
) t" h9 I+ Y4 ~/ {/ D% J% f( G% D        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);" e2 T0 \$ x; q) T: [0 A* S
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);( |# h7 [# X" Y1 @* ~, y
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
6 U" |1 `( b  E3 D, e        studentVo.setSubList(subBoList);
' d5 D9 d# E! k2 `    }$ o( B2 r4 u4 n$ g
    return studentVo;/ [# R9 K8 O. I5 X( \7 _% ]: y
}
" w, B8 h7 {  A' B" _</code></pre>
. F+ c% u% J, u<h5 id="2理论分析-6">2、理论分析</h5># w& Y* I# r! P
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>5 D6 j& ]* s1 \
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>, u& C$ J" X3 Q9 D6 Z7 ]3 {
<h5 id="1示例代码-7">1、示例代码</h5>
' ~9 v6 b5 C5 T. D& w<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {7 u& c$ O6 m5 l9 D& c, r! B
    // 通过主键查询学生信息
. K2 M' F- P0 W6 P: A    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
* ~4 e/ j& a/ I! d4 \' b2 t& n    // 批量查询学生ID
2 Q) x. i* Y, R! R    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());7 l) T) W) p1 e4 U$ N4 @; \
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
, f+ l- B4 g# g& ]. S: X    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);0 ?4 i, v3 [' I8 k
    // 批量查询课程ID
1 }3 I. e: X+ U! f4 k3 v0 O8 d# a! p    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
- r' z4 s3 R' P- `. B1 r" k  G8 \    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {* R+ B. ^) L% E, f; Z( g8 @6 a
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
/ V" r% z/ W$ E$ J        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));9 y' h3 }6 t8 ?) z
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);! K1 P/ ^" a1 [; \/ k8 {5 s5 t! I' T
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
* n' [. j9 b. i+ j6 T" c        for (StudentVo studentVo : studentVoList) {
# N1 z  k2 R  l% s- S6 a            // 获取课程列表9 |+ V- w8 w) U7 x! R" g
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
+ E) w0 ^& C& o. X            // 填充分数
1 |+ v. L$ D( Z3 D            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));6 l& |) @6 E+ I1 C7 v3 K5 J4 r; o
            studentVo.setSubList(list);8 x+ a$ v$ H7 `3 D) r
        }
" `5 D) V6 F4 S' v2 k3 e( G$ f    }
2 l6 q5 D6 u3 z( H8 Q    return studentVoList;
5 |! P3 d7 {, @* }" M% J, h}
' _6 w* Z& G. O</code></pre>' z4 a3 ^/ ^3 `+ ^& E
<h5 id="2理论分析-7">2、理论分析</h5>
# u5 q" H0 U& E  s<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>* Q1 f0 l3 n# |" J* q
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>$ k8 G' ?# r# q7 [- @2 E
<h5 id="1示例代码-8">1、示例代码</h5># {' ~" z( r5 Y) a- J2 j
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {( F7 t" K7 k! E! N: I& K9 C
    // 通过主键查询学生信息* X0 l% G# c& a4 Q
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
1 Y' o3 `/ @8 ^0 s    // 批量查询学生ID. C; S' s7 h' k( A7 X, p
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());3 E/ ?" K7 k) e! v
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);1 \2 V2 J9 p$ h1 u, X
    // 通过学生ID查询课程分数
3 Y# S2 U! K: ^) }" X    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
  p* O9 K  j$ Z! N    // 批量查询课程ID
* t2 z' N5 a" H, P    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());; k/ L( n& a; \; j
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {! e- e2 a9 X- T3 q# m' o% b$ s
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);, O% a* W' x0 e) _0 X
        // 学生ID查询课程ID组# r" l) p" n: l9 s( Z7 }% s# A
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));/ h" d9 t3 j  u

# y7 C: l* N! g$ s8 |7 f4 ~: [        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
7 M, V3 a7 v$ X$ D$ P        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
( [* M' z" I/ i% t9 I3 ?        for (StudentVo studentVo : studentVoPage.getRecords()) {
2 v! l( W5 x6 x6 A+ B& |% K; h            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));; b0 Q3 V3 C1 k7 p
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));- C: o8 S/ M+ a- i2 X! X$ m0 S! s
            studentVo.setSubList(list);
; h4 |1 o- Z# J2 V* C0 o% V        }
, r: U0 q- I6 S' J4 o! V! t    }
8 l5 P3 D/ w: S/ b* K    return studentVoPage;
" p) m- \  n* ]" }: O3 ~}
' e% u1 M. N5 O) `$ I1 @- ^9 ]* X</code></pre>4 t& L- G8 j5 v' x$ C3 X
<h5 id="2理论分析-8">2、理论分析</h5>8 V, S! p- _& R- h- c5 a
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
% L) g/ e; J- \3 b! T<h3 id="五总结与拓展">五、总结与拓展</h3>  ]; M6 P1 b) l
<h4 id="一总结">(一)总结</h4>* r3 {; P* D; V0 \8 i
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>- B2 z1 }& K7 ^, j3 j$ y0 {
<ul>
) _5 _" w0 L# \<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>  w& |( i& I5 k4 G1 t  I
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>  v* ?- p* y; M2 j
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>8 n, c  ]% a$ ^  Z* `. r3 W
</ul>
, |! G) X  U+ i- j' w<h4 id="二拓展">(二)拓展</h4>
2 p+ o2 f, i$ T; D# r1 p  ?4 E<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>! P! o# ?5 E% w0 G, h9 q
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>& D  x- }: n& d! v
<ul>! r5 X; F, n0 x1 o2 W- {% U+ c3 c
<li>当数据量较大时,仍然具有稳定的查询效率</li>
8 ~4 O- @5 @* W</ul>4 Y$ ?/ D+ q& E+ {, Q5 l1 V8 R, @: M
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
3 d. r* |2 `, _<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
+ l1 A  T' P4 x& o- G9 l+ u: `<ul>$ L) A% s; N& n" w( K4 a  P0 T/ t8 s
<li>与二级缓存配合使用进一步提高查询效率</li>. U/ ~9 f8 m7 X8 @3 L& a
</ul>
0 w6 }8 v! i3 l4 i  m# D<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>* i5 Y1 a$ K5 I4 w( l
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
8 k0 u# C* X; K' h( X/ o+ g8 _& v, ]% v' _$ L
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-5 08:20 , Processed in 0.129957 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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