飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8239

主题

8327

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-1-12 02:53 , Processed in 0.068867 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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