飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7992

主题

8080

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-11-27 17:59 , Processed in 0.069223 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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