飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8194

主题

8282

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26912
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
& ~, n" j$ R  |! @
<h3 id="一序言">一、序言</h3>
) h1 f/ E& g2 }  `* x* p2 |<h4 id="一背景内容">(一)背景内容</h4>0 O4 g$ E: w" ]5 Y* Z# Q
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>3 k! W; h8 H' b- n1 r
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>) W& {; Q8 L2 G
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
  G* |$ B5 ]( V6 X5 A0 ]: b<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
! w  B/ y- `% ^! j/ c1 L<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
8 ^" v: B8 C. V<h4 id="二场景说明">(二)场景说明</h4>
( S/ Z( x: [2 [0 ]( F4 N<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
1 E( Y( X! S, ~) W3 S. E<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >7 Q, S0 t. b: `
<h4 id="三前期准备">(三)前期准备</h4>
6 ~* T1 T& F# W; ]$ l<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p># f0 e; H7 a1 P; C9 _
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
* ?0 x% N. z0 b* D8 Y/ l% `3 b' p7 K<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>$ i$ W2 p1 p. }& v5 m
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
9 [$ k" ]& p+ R7 V<h3 id="二一对一查询">二、一对一查询</h3>
8 g7 [% x" r! W9 T6 i<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
* k! ~; K. |8 g* E* p# ]0 ]<h4 id="一查询单条记录">(一)查询单条记录</h4>3 O3 }# y$ g3 [( b
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
' [! a% }( v3 R  P<h5 id="1示例代码">1、示例代码</h5>, y4 w+ Y6 k) I" A% _4 c
<pre><code class="language-java">/**
# m2 J' T! M- R' {  d) S! X * 查询单个学生信息(一个学生对应一个部门)
* j& a. q: _' ^( j7 k( Z1 N *// [3 d8 z) b' X
public UserVo getOneUser(Integer userId) {2 g9 U, W  w1 C8 w
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
7 Z: Y* D4 P  w- y- F        .eq(User::getUserId, userId);, M0 f: e0 C- |  s7 c7 E
    // 先查询用户信息
; C: ]0 k; G3 m; n% p, G    User user = userMapper.selectOne(wrapper);0 q% G+ T: e5 Q- c; t8 J: R
    // 转化为Vo
9 t6 u* Z% f) t! E    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
1 {9 A+ A7 ~" n  C, E, M* f    // 从其它表查询信息再封装到Vo
' W$ `- }+ r- |7 _. _    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
" K* w0 X; B, b! z: z9 s    return userVo;( Q  s- Z  E3 d  M
}
7 y% ^8 a! s  C8 U  [9 O: ]6 O</code></pre>$ e5 O7 N+ Z  s# \
<p>附属表信息补充</p>% L( w' I9 u7 d( ]6 P) d, o6 k
<pre><code class="language-java">/**4 ?1 w! m* {' T1 N$ R8 i& q
* 补充部门名称信息
# w# r6 C" S2 x$ v4 z' g */
0 J* w- m5 u6 s) I: L; Zprivate void addDetpNameInfo(UserVo userVo) {
4 j4 u2 W3 i5 w6 g0 F6 {    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
3 M9 [8 |5 C  T        .eq(Dept::getDeptId, userVo.getDeptId());
& ^4 G" K- m! O- B$ i0 z    Dept dept = deptMapper.selectOne(wrapper);
4 W/ g+ Z( I% m    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));2 Y6 w. q5 f" \# S: Z$ C+ W8 E4 n: ]9 t
}
8 G4 @$ g- f+ [% q( u) O</code></pre>4 ~5 [" i. z" I" C% z9 _
<h5 id="2理论分析">2、理论分析</h5>
- J7 ]: j* I5 M/ J, e<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
% @+ w7 F: k/ W  u" a. t1 N  ]5 T<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
) P) }* L4 J$ N' v5 I  N<h4 id="二查询多条记录">(二)查询多条记录</h4>' v+ o5 ?  s- v" X
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>3 S3 |) ?# Z- F* }- V* t" D! t
<h5 id="1示例代码-1">1、示例代码</h5>7 G6 P8 o8 T% @: ~# }. g" U8 \# D
<pre><code class="language-java">/**
! o# p% F5 I+ q0 {  P* K) H9 m7 Y! s * 批量查询学生信息(一个学生对应一个部门)
; D6 F$ R6 F0 X& y. |  N */2 H, G0 `9 N6 [6 T1 o  i4 ^
public List&lt;UserVo&gt; getUserByList() {
5 s3 f+ B% W6 r3 ]- u0 Q    // 先查询用户信息(表现形式为列表)
. h2 @, Q  U3 L    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
2 e  `( f! J. c6 M9 i9 p* b- \    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
* [3 z* ]6 e  S) e5 ^  \    // 此步骤可以有多个
! _5 m5 k2 {  X  `8 ]8 ^+ l    addDeptNameInfo(userVos);9 ~8 d- q  A) W4 x
    return userVos;
0 K3 C3 c( k" }5 Y- _% E% R0 O}
4 i8 P8 r1 I+ `3 U4 A& {/ h- t</code></pre>
! n- G. K% F9 Z4 m<p>附属信息补充</p>
" q- G8 ?- [- }  Y  Z. t& X<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {3 M" U5 h4 p- A: ]" _
    // 提取用户userId,方便批量查询
4 O$ `$ o) G5 Q2 H: d    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
& i0 u0 H* @0 I5 w' D    // 根据deptId查询deptName(查询前,先做非空判断)
3 q5 I2 F/ s( @" u& U    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
) X# H) F( _* Q6 n; D0 t    // 构造映射关系,方便匹配deptId与deptName
  }' w! c! e' u- n% {9 |0 D    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));4 _/ v# Q. ?0 d: _) ?+ X4 b
    // 封装Vo,并添加到集合中(关键内容)
) C, R: ]0 v" M  s+ Y    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
* M' {% c# B3 t7 }) X( A1 m}
5 `" u$ u0 h1 Z* Q</code></pre>
% Q+ N0 G! Y7 J, }<h5 id="2理论分析-1">2、理论分析</h5>" g* p; A1 P& \8 i) {
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>2 U8 i) {5 ~. T% f: @
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>6 g/ ~8 A4 E0 t( E7 U# q
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
9 W7 x* g' N" y# O* P<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>5 G3 ?7 J- Y4 l; j
<h5 id="1示例代码-2">1、示例代码</h5>
& ?9 g7 A9 `- d" j1 [0 S: W<pre><code class="language-java">/**
! \, h. s- f: |$ [. J. u * 分页查询学生信息(一个学生对应一个部门)8 @) Y$ z+ k& r7 l( O
*/
7 l" l7 _) T. [( X- [4 M: d/ {public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
1 C* i/ M( N8 {6 A0 c) b    // 先查询用户信息
1 c+ F2 z/ M6 g    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());, I4 Y3 N0 e4 \8 E6 _% z
    // 初始化Vo
' f* j/ e0 B) M; p7 F+ Z    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
' {& w) G) Q% m2 D( ]    if (userVoPage.getRecords().size() &gt; 0) {3 b4 q: F2 V" F% Z* a, J( V
        addDeptNameInfo(userVoPage);
: k, y4 N% ~" z/ c% D6 z6 D    }
7 o) M- K+ E6 R% k5 u5 p    return userVoPage;
1 x7 v% p* k4 T$ t% w}! i3 y( M7 e6 R$ V
</code></pre>' U" h0 D9 u9 H
<p>查询补充信息</p>
2 Y. z+ r, ]* r# p# y<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {9 d$ r. t6 w( f( ^
    // 提取用户userId,方便批量查询
& m$ L# u% E& q: ?) o$ W    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());4 Q( H5 _- J5 f' w, Q. [3 K9 w
    // 根据deptId查询deptName6 W: P9 `/ ^7 u$ R7 y2 \
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));7 W8 H& K, U. Q$ v7 c  Q7 ^
    // 构造映射关系,方便匹配deptId与deptName5 c9 w+ [# p/ Y, {
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
7 C. v0 S  `) D0 C    // 将查询补充的信息添加到Vo中0 k) F, z( j0 S
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));5 Q7 o# b- {) r' @- l4 A$ q
}
4 v4 V7 O) S3 a: [. _3 Z</code></pre>
% U3 D* z$ f% t9 S<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
& ~" q: `- F* k) o, `<h5 id="2理论分析-2">2、理论分析</h5>" B4 ^7 F" N5 C8 [* C$ ?1 c
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
: y# Z- B1 z+ W1 J$ ^<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>: _- B4 j& ?1 L3 I+ |+ e$ y
<h3 id="三一对多查询">三、一对多查询</h3>
+ }/ Z3 O. Z7 c) a4 f8 F7 D. J<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
1 Q2 t* H8 v7 E) Y5 u$ m5 z5 A4 [<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
1 \8 M* l5 R( Y( y" P! I; g<h5 id="1示例代码-3">1、示例代码</h5>
4 ?: n9 `! R4 p3 {; @: x, S" M<pre><code class="language-java">/**9 u/ c! B4 }8 W- L7 ], W; A
* 查询单个部门(其中一个部门有多个用户)
" ^( \9 t# A3 Q) A  {( e */
+ r2 z) V9 w+ a: g3 ]) t3 Rpublic DeptVo getOneDept(Integer deptId) {
" y3 z/ Q- Y! Y) [( R    // 查询部门基础信息6 |0 I- e8 [* j
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
& V3 e4 o& [# ~    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);, l. n1 o# r* ?% M4 `
    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
  |* k; B7 I' R7 Y    return deptVo;" B! O6 Q- S4 f
}
: x  T$ r8 T" d1 ?& {) D- ^9 H</code></pre>
9 s+ U8 X( S/ j8 r" q" d- T<p>补充附加信息</p>  o" q/ I% N/ `3 j5 |. d  X* M
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
, `" E& i" |6 `0 ]. _! Z  e    // 根据部门deptId查询学生列表
$ X  S) O/ x+ i5 b& E7 m5 y    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
( Y2 Z* L, v7 s! ~+ N    List&lt;User&gt; users = userMapper.selectList(wrapper);6 ^  w4 `. f& c( n! B. S2 J
    deptVo.setUsers(users);6 O0 G7 D1 S2 g( \5 D
}" o* R0 [. e; `. ]/ y
</code></pre>
" j7 h8 W* G2 J- p; ]2 O# o<h5 id="2理论分析-3">2、理论分析</h5>
1 ^5 d8 ^+ M8 e3 t- h6 I! y3 n<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
; \3 E4 i' z" b" K1 k<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>9 X' j" H7 }7 F9 N& c
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>) `7 E! }- g% R: `
<h5 id="1示例代码-4">1、示例代码</h5>
/ }, o% n! K4 s<pre><code class="language-java">/**  J7 R" }1 G' ?* W8 G- l' D, v
* 查询多个部门(其中一个部门有多个用户)
; `5 ^& U) u5 r9 b$ U3 B  `4 M6 E */- S/ K8 n' L2 W; X* V( n5 h& t
public List&lt;DeptVo&gt; getDeptByList() {- k6 C2 w. B& N* _
    // 按条件查询部门信息- b! ^* o5 @8 ~4 Z+ n; x/ R
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());% d/ q4 _: V3 D& |) F
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());: p, o2 j6 ^; i" S
    if (deptVos.size() &gt; 0) {
' C- C  I$ u8 p; `        addUserInfo(deptVos);
5 p1 T4 l, P* v    }
0 J# ^" Q8 F. U! C- ^- z; l    return deptVos;5 M1 y2 X- i3 X, D' |1 R! I
}# ?( v" z0 A6 y  |  ]5 _
</code></pre>
: f4 E# A% o8 Q! c/ p$ L<p>补充附加信息</p>
0 s: _5 N1 v, {) Q<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
* h) n& I/ x. b6 @1 H: G5 e    // 准备deptId方便批量查询用户信息
, V! a& [5 A$ s( f$ B* b    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
6 a3 ^! Y4 y! ^! d0 O$ [    // 用批量deptId查询用户信息
% W- ?" q4 r5 {    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
. Y% W1 ?# v% n" A4 ?    // 重点:将用户按照deptId分组' d5 q# y2 b7 b
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
5 X/ N2 O8 R& ?4 @; g, [    // 合并结果,构造Vo,添加集合列表* a6 s( X9 k- l, ~7 Z0 ^
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));& e2 l4 m& h& p" c' L+ n
}+ E# U# w" K/ ~" I
</code></pre>
. j1 h: V* O3 H3 \; j# `5 z; K<h5 id="2理论分析-4">2、理论分析</h5>% Q  K9 s8 F9 k. @& @) f+ A& _9 O5 T+ Z
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>1 W, w$ ?# s5 p8 j
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>* S# `4 ^8 N% T" g! W8 Q+ X
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
/ u' F1 `- e; w3 v9 i<h5 id="1示例代码-5">1、示例代码</h5>0 X, i! [  V" e# \! e# n* H: ^
<pre><code class="language-java">/**
0 v; o5 R6 g$ u8 g& _4 M * 分页查询部门信息(其中一个部门有多个用户)
) l4 q* V+ ]: U) y4 q */
8 j4 Z% r( m' m$ d" Opublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
8 Y$ h, c# {1 Q1 }0 T( ?; u' z    // 按条件查询部门信息
8 D1 w2 u: J/ W* S    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
, d! P+ ~3 U* ^5 X" T5 }4 f    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);: X/ k+ |2 l9 U) P. ^6 ?
    if (deptVoPage.getRecords().size() &gt; 0) {, `* F3 [+ L0 q( t
        addUserInfo(deptVoPage);' q! n1 L* n9 \* Z
    }
: f4 x+ E* p) @3 k$ M" {+ A8 t, g. n    return deptVoPage;
, P7 N% G( `, |7 g0 b' y}
2 c% \0 @$ G$ M8 Y3 G- u</code></pre>
2 E! {$ {. f9 c& e6 j5 l<p>查询补充信息</p>; w6 b; |4 h5 i7 L+ @
<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {. M' I6 N' F4 d, ]! M2 e
    // 准备deptId方便批量查询用户信息
9 D9 A7 H' t. v    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
9 \, a6 X: Z6 p) d( V    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
8 M7 c: r& @6 G/ d/ q1 n    // 用批量deptId查询用户信息
, D8 {4 `, n0 t" R* R    List&lt;User&gt; users = userMapper.selectList(wrapper);
' _* E% Y7 L% |& j# ?& O) ?+ P& l+ P    // 重点:将用户按照deptId分组
. t0 ]  i- J7 M5 X* E3 _" f* Z% |    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));8 t- d! ]: N) z! {9 v0 Y! C* A
    // 合并结果,构造Vo,添加集合列表" U* L+ d0 c. x
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
) D+ y) j  O. G) t) A' m}
8 F% }7 L7 E& [. ?4 V$ a9 ]. j</code></pre>9 F9 I. Z0 {0 @
<h5 id="2理论分析-5">2、理论分析</h5>
/ u% o5 ?" ?  B  D<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
* `( h# Q- I# x) P<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
: J; d8 U% J; C% d9 r<h3 id="四多对多查询">四、多对多查询</h3>
, }3 K6 i  \+ \$ G0 m/ ^<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>; V9 l7 g8 K" X3 J0 v
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>' ~, D" Q. R4 A# m
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
2 }7 ?, J$ C6 K9 Q1 Z! ^* t  Y/ K0 L- \<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >5 B2 T- c1 A6 I* W, L
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>5 g1 |$ \0 v; P9 Z3 ]: p) X2 r
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
' B3 c+ M( \, {8 t# B5 @<h5 id="1示例代码-6">1、示例代码</h5>; A( |* Z6 g$ t6 S2 h
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
) ?$ I' Y* O* F: K4 y) o( m, `  |    // 通过主键查询学生信息; T+ O5 z3 W  t
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);& D, w/ V! J  q5 M4 u
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);- Q/ R+ H: x+ e0 t! B/ Z* ^4 J+ [: o1 z/ R
    // 查询匹配关系$ E9 U# o  q2 x8 i2 \
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
( m% c, @+ c/ ~+ `    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
) L" K/ F- E: e* l& W  g5 H    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {4 ]$ |! P* f$ S1 X# f+ H, {6 @2 E
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));* v$ t, Z* i% @- c; t
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
7 O7 J) B, _6 o% W0 J+ G/ z        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
; |; J/ G6 z' s& W        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
( D* Z) a/ x$ R        studentVo.setSubList(subBoList);- L& U5 C( m/ ?$ _- l* K0 j
    }
" T; t9 R7 S8 o1 B6 u    return studentVo;
1 n$ s, ]; S- G) S2 ^$ }/ R}
# |3 ^. n+ r# k6 U</code></pre>
; l3 V$ P7 t* l" ~% R) \) O, t, Y<h5 id="2理论分析-6">2、理论分析</h5>; b) s2 t/ ]/ ?
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
4 E) A1 [0 v7 y0 T<h4 id="二查询多条记录-2">(二)查询多条记录</h4>0 F; y7 {. R8 U6 C5 C( _& U6 m
<h5 id="1示例代码-7">1、示例代码</h5>+ h/ F1 y: f& z* [  n0 U2 ?8 I2 j
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
( B$ Q2 J- B9 I: G  e& s. `8 P* B    // 通过主键查询学生信息, W( }' H+ _) |7 d  w. E, |3 a
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
% t7 F0 T+ z. N6 [4 K    // 批量查询学生ID6 E; b# \$ r. S( J
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
. I! u+ J) `+ H% p: g    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);% v7 _# n5 a% L
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);" J. _" S8 R( M2 @
    // 批量查询课程ID5 Y5 w3 e8 y6 F
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());( Z; T* F! j$ P, J4 [/ ~; x
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {, S( ~0 |* \& l+ z
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
' [2 f( `' Z7 _% R. Y; c. M        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));1 r+ ]4 k" g+ W% ]
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
/ i- G, t0 Q1 t( k        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));3 k2 `' ~0 C# r3 i
        for (StudentVo studentVo : studentVoList) {0 L( \9 _- g6 G3 r+ \" J4 G
            // 获取课程列表
: I& S6 _  D8 D; |            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));- H" h$ s' ~* ]' [8 }! Y- H
            // 填充分数
2 P! ?! m8 w4 R) s            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));2 x" N4 C1 [/ B/ O! ^- w
            studentVo.setSubList(list);- ^; Q/ @! d: ~6 D- {" G0 v2 j
        }
, {; M: f; L: S  v: p. u& j7 U    }
  E! [& v( ]5 j4 x* o    return studentVoList;8 `& A1 D5 L5 T# E3 N
}2 s  V* N; Z/ ^! l! F& E
</code></pre>
" D! l5 B9 t; c7 L6 r<h5 id="2理论分析-7">2、理论分析</h5>
4 [- w) }: p+ J' ]3 f( X. B<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>% ^) w% D7 C3 j# o6 W5 x. N5 v& {$ J
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>- N# b1 Y: H8 @' ~/ n3 ]
<h5 id="1示例代码-8">1、示例代码</h5>
6 L5 m( {+ D( n$ ?<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {+ |) n$ g  {7 b/ v4 B1 c6 A
    // 通过主键查询学生信息
9 s9 A; K2 K3 h3 y. i% Q    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
1 }6 r* b9 n$ l+ R. J    // 批量查询学生ID* c% Y2 S; w& T" _% y& @+ ^4 M; o# b6 W
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());2 N3 n" }7 z# x7 l9 V
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
2 T. R5 }8 ^+ ]: X& g* S  K0 k    // 通过学生ID查询课程分数" x2 p, C9 p% d) s, t
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
) m8 Q7 O8 t5 l9 c( p9 e4 |% l    // 批量查询课程ID
1 t) j8 A9 I- _+ Z$ ]    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
1 i* X: M. M" D5 I+ ~    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {) T0 p9 l. A- V* t; D! E
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
/ |0 r: }, D- Y7 }8 B. b. l6 I) `        // 学生ID查询课程ID组: s/ G, @1 N1 o/ |- ~
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
+ f* G$ B$ E* \5 V* h' ?
- }% o" A5 m" @' d6 U; M        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
5 S8 H; d; ^7 K        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
; ^7 P1 F: u0 x% t        for (StudentVo studentVo : studentVoPage.getRecords()) {
# Z" K# s4 q" v& |5 @& g. u9 r            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
/ {4 k- X. Q/ I0 \/ ~$ c. u            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
, Q$ [0 _2 E& V            studentVo.setSubList(list);
0 \# |% V8 V7 a, y# ^; B8 L% c        }
0 Q1 Y+ x- E/ Q! g4 [    }1 P5 g. L% i) e+ w1 _6 W) d
    return studentVoPage;' V) Y, o% Q5 ~9 X/ C$ S2 e1 Z9 V
}, A/ x7 \% I, b* ~
</code></pre>
- J/ \# ?4 }" _+ j* P1 o$ g$ m. z<h5 id="2理论分析-8">2、理论分析</h5>
" A" Z4 I- W& v' z- o& l+ k, H- K<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
, c2 N! d6 f2 r! Q' s<h3 id="五总结与拓展">五、总结与拓展</h3>3 D# A' q; q* E$ r
<h4 id="一总结">(一)总结</h4>
4 W" d8 R$ t" s! D/ Y<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
6 V5 i' D' Q6 W<ul>! l; ^3 P3 x( `7 @3 m$ J
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>& n( {8 }  Y8 }( D7 U3 ?
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
! u6 e" \! Y) M4 e0 \% A* B<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
$ Q+ s: |0 c  Q4 X# \* X, G</ul>
; s% Z( H; L; P4 a) ]  q<h4 id="二拓展">(二)拓展</h4>, a# L" L3 J) c! i& u0 F! Z3 c3 G
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
( P9 W3 l! `# ]! R1 u<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>" W; R& P3 j, }/ `
<ul>
( L, P3 X2 O0 }# C<li>当数据量较大时,仍然具有稳定的查询效率</li>
2 f9 T! R2 `: G- C</ul>
9 y$ |. D% k1 C2 O  p. a<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>& d$ [9 p- M3 x! z- S- b
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>- B% q% P0 q% K! `( {
<ul>5 @" F6 H+ L3 A& a( c. K
<li>与二级缓存配合使用进一步提高查询效率</li>
* y4 H7 W3 p) x, k5 g0 t% |</ul>8 _( H  C2 Q4 S6 z
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>/ R2 g- Z; u5 K7 G: N9 q
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
% U. z+ `8 u1 c  u* t
9 j7 s3 @) y/ L4 G
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-1-9 00:02 , Processed in 0.066066 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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