飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

6861

主题

6949

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-7-3 09:56 , Processed in 0.067794 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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