飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8194

主题

8282

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-1-8 21:08 , Processed in 0.070677 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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