飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7587

主题

7675

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-9-18 14:21 , Processed in 0.072669 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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