飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8135

主题

8223

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26735
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
' y  @  A, ?" K8 K
<h3 id="一序言">一、序言</h3>
  o$ B1 Z1 t9 U" n9 C# A% B/ U<h4 id="一背景内容">(一)背景内容</h4>) i# H' T5 V  L
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
; ]) H) D' O9 R6 e. n2 |<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
( k3 @* @; ^% Q: Z% B. x<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
6 U' S% [; F+ Z. L/ G) a<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>0 o1 p' J( C7 z/ @0 @! j
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >5 c% T8 H2 D" a, X8 u
<h4 id="二场景说明">(二)场景说明</h4>
4 W% u( B. X4 g$ D7 y5 S<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
3 z' k( u/ G- e1 K' i3 j<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >( h4 W/ ^6 L! n% o8 r2 X# D# ~
<h4 id="三前期准备">(三)前期准备</h4>. D$ e) d9 }' e- o/ `  q
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
* N/ K$ q# a; `/ a9 y6 c6 D$ Z<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >; O. F& ]+ q3 M- i6 w
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
( h2 ^- v- m8 q8 ^% y& T<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
/ a$ n# c2 l' H) i5 }! l# Y<h3 id="二一对一查询">二、一对一查询</h3>% C% S9 w; ?" A" S: _/ S
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>. x2 N8 ?. s' k  O/ U
<h4 id="一查询单条记录">(一)查询单条记录</h4>$ z3 q$ ~; t5 I
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>" b1 T5 [+ B8 t+ [  Y2 r& p
<h5 id="1示例代码">1、示例代码</h5>$ V4 i3 }; H( a6 B
<pre><code class="language-java">/**  a. o! Z; X- j: x
* 查询单个学生信息(一个学生对应一个部门)6 @1 R# ^8 c5 e; I$ I$ ]
*/: P" U( W; p) n) H: g: Y
public UserVo getOneUser(Integer userId) {
: `5 F3 j' @( i' d6 H    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
9 X  u3 q( t6 G  ~, V        .eq(User::getUserId, userId);9 Q: K* V+ Q- q" z0 k5 |2 t) w
    // 先查询用户信息
1 M  G6 B3 I# k9 p* u7 v4 u    User user = userMapper.selectOne(wrapper);3 \7 j' y) i# B$ j& }" C6 ^
    // 转化为Vo% s3 A5 e1 H: d* R2 w$ l- B
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);6 ~0 o, j; D8 O4 i
    // 从其它表查询信息再封装到Vo
8 @' }% W' @  f1 N+ v( ~6 l    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);7 e- _# o+ D5 Q( h
    return userVo;  h2 J3 n( d4 P  ]
}( G% r( @5 p5 ]& ^) k0 G; a$ R
</code></pre>
( E5 u, ~& y' M: t3 ]<p>附属表信息补充</p>
6 |& d  T# k! S" {( K<pre><code class="language-java">/**, K' n% y: N% r3 Q$ A
* 补充部门名称信息
0 W& B& a. Q, x& }% t$ z, T */
! d+ S0 J2 \/ V0 L3 `& p4 Kprivate void addDetpNameInfo(UserVo userVo) {
* s* T6 T+ V' c3 C    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)% G8 _8 X3 `  |" \
        .eq(Dept::getDeptId, userVo.getDeptId());
" q% E& V& e- _    Dept dept = deptMapper.selectOne(wrapper);
( T* u5 F2 F, H+ F. P/ T    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));% J, Y. a- j; W- u( o
}
: T( M7 Q  |4 V" B4 V9 p; i</code></pre>$ |& V& E+ ?3 \: I7 A6 i! ]
<h5 id="2理论分析">2、理论分析</h5>
# m& P. z) E, D& u! C( C3 q<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
4 `1 K7 |" I0 u2 m3 o<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
: o2 c4 v0 w1 ~, {9 W  a9 T<h4 id="二查询多条记录">(二)查询多条记录</h4>3 W- ]0 C& E8 i& [! S4 i
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>& T; c, A. q) ]* a
<h5 id="1示例代码-1">1、示例代码</h5>* \- v9 i; S9 ~: G- q0 L
<pre><code class="language-java">/**. r7 M/ Q0 m% P3 `
* 批量查询学生信息(一个学生对应一个部门)
7 d4 V* d7 w; Y( K */- A; P6 r7 S! T% X, H* t( \
public List&lt;UserVo&gt; getUserByList() {
' @3 M( U( l! J. |    // 先查询用户信息(表现形式为列表)
5 \; \- K7 f# u" D    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
! A' n3 r) B, k5 b, g    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());9 n( N& l8 I3 s- L( V/ L8 P
    // 此步骤可以有多个
+ x- v7 J0 P& a% g    addDeptNameInfo(userVos);
! E& ^! t2 m: ?4 h    return userVos;5 G1 y5 Y2 H. r% m0 R( i% N# ?+ G5 ]
}1 D# h# k. |- Z! f6 \# t! u" j# I
</code></pre>
8 L5 g; n; f2 Z9 i5 h0 ]<p>附属信息补充</p>2 n2 |$ p8 A$ u' F* C6 l
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {) }6 I4 Q( W% m9 n6 A
    // 提取用户userId,方便批量查询
) E: T/ P. N6 }) d! q/ u& h    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());3 S+ S; t: }+ b5 C
    // 根据deptId查询deptName(查询前,先做非空判断)" A6 L8 E, p5 e) {! \' R
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
2 z" u7 a8 p# U  G0 S: d    // 构造映射关系,方便匹配deptId与deptName
, u; R+ d: ]1 i& c$ G: K# F# \) O    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));& @" [. y' ?% \0 a3 ]
    // 封装Vo,并添加到集合中(关键内容)
& W" E( n, J$ A6 t: e7 \    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
+ W/ q+ ^  S4 h' d' w}
: l+ ~$ B3 z: k: L. U6 N: D</code></pre>. F% c5 ]0 ~7 M& V
<h5 id="2理论分析-1">2、理论分析</h5>7 Z" k" M3 w. v- v; c7 F8 L; N
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>, v& w/ e  r8 E( y% ^% s# `
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
/ [+ k9 Q# z3 `& e' i' j5 R<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
! I! E! N6 N0 T( j5 E& d<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
! ^0 |- _6 Z& H! D  a/ k5 J<h5 id="1示例代码-2">1、示例代码</h5>
# r" A5 p* z$ z<pre><code class="language-java">/**! k4 z2 I/ Z/ [8 P6 t0 [
* 分页查询学生信息(一个学生对应一个部门)
" M7 t! b: h5 f, H: M */
% d" v% x) b* j& p/ T4 n, ypublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
8 x8 h) I, u$ u( N2 }+ q* U& P    // 先查询用户信息
  [% y4 q! x: j+ P5 s, N" Z. Z0 z7 v    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
6 G- R/ q( D. O0 ^' B9 M    // 初始化Vo
2 y* y8 e+ h0 P7 p, L    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);& c8 r6 A3 j+ E& O
    if (userVoPage.getRecords().size() &gt; 0) {& A$ c5 ^0 z4 C2 \$ E9 k! m0 }
        addDeptNameInfo(userVoPage);9 F% H9 h6 I5 t' \- ?0 _
    }
2 x! p+ _( t2 k    return userVoPage;
2 b1 l0 t- i( g; m. W}# o( t% u/ S: I8 h7 G
</code></pre>
0 N( |$ z- d6 ?0 z5 ]<p>查询补充信息</p>
2 W- b$ [4 m& q) X<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {" o2 ~8 t: f# ]' T) f/ n
    // 提取用户userId,方便批量查询
* A2 f+ @+ M. M8 ?    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
5 A9 r+ B- T$ \8 H6 ~    // 根据deptId查询deptName3 H$ `. M7 e" R  }( s3 ^3 t
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
3 z+ F, z8 Z0 w# C. {    // 构造映射关系,方便匹配deptId与deptName7 W/ y% u" z- V! G, i
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
; f, D9 `% A" D& I' J    // 将查询补充的信息添加到Vo中
3 Q* d! \, [( c    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
2 u' ^. e& p. `}' n$ p, I1 U0 C0 p4 y' e
</code></pre>  c0 Y  K% P) a: t0 V
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
7 P) X& h# \4 U* H<h5 id="2理论分析-2">2、理论分析</h5>
- x% n, Q" N( G' p5 R6 i( L! ]* Q<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
% p& S% W* C8 i/ x<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
2 M0 g2 e& [0 t& _$ q<h3 id="三一对多查询">三、一对多查询</h3>( q" B$ ^3 e' C! A
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
4 ?5 s5 M# z, Q8 w4 [" ]) I<h4 id="一查询单条记录-1">(一)查询单条记录</h4># P1 Q4 `  R& X9 j# s3 y% L8 X
<h5 id="1示例代码-3">1、示例代码</h5>
8 P3 T; `, J" \, _% T/ b5 A<pre><code class="language-java">/**
" I/ m4 E8 j* w! T9 _ * 查询单个部门(其中一个部门有多个用户)
( j1 N8 s: @6 A6 n& J */% D" u5 f% L! e* U7 M0 Z
public DeptVo getOneDept(Integer deptId) {* ?: |$ B, l+ [1 k# P9 o$ M
    // 查询部门基础信息
% n: @5 y3 \3 W0 {; W    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
7 \% b7 @( Y" [& S4 p' _! j! l" ]6 t    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);; m( ?$ g7 Y& A" A4 d1 g2 ?4 V
    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
: V) T6 @. V6 q, o    return deptVo;
  n' C1 [7 ]2 X" r" z/ F4 L}
1 }1 G* r1 N- [) A" [</code></pre>, |9 u' g: b: j3 w
<p>补充附加信息</p>
9 N/ S; U/ P! ~+ b7 S<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {; h. z" v3 J3 p  |
    // 根据部门deptId查询学生列表
' s' J* q6 d6 [' T2 T    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());; n8 M+ o! i, V3 G0 q
    List&lt;User&gt; users = userMapper.selectList(wrapper);
3 w6 |; `- [0 j/ l    deptVo.setUsers(users);$ Z: W" q0 G0 \, D
}
0 Q2 J2 {8 b# m* u</code></pre>4 {, f6 g( ^) O  d% h8 r+ O) C
<h5 id="2理论分析-3">2、理论分析</h5>
  S3 N& K- @- ?; j! I% M2 o<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
; ~  P! R# s9 U% e* u4 i# p<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>* N+ O1 U, r, b' }4 L0 [5 @0 I
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>1 ]* F* B. z# }* Z5 u6 ~$ V
<h5 id="1示例代码-4">1、示例代码</h5>6 X  f8 f/ |) p8 b- b
<pre><code class="language-java">/**
, I' q2 @7 u0 o  L; C * 查询多个部门(其中一个部门有多个用户)2 t; v( J4 Q; ]5 i
*/
% A4 e0 W7 M- s9 cpublic List&lt;DeptVo&gt; getDeptByList() {
3 q5 c: `( i& s4 A0 P) r; W    // 按条件查询部门信息
3 p( [& M% E5 D7 w2 }$ j    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
) f* J- \/ b: Q8 s8 k3 ]    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
5 v/ D) ~+ B1 b6 a3 A( K    if (deptVos.size() &gt; 0) {
8 Y" p0 S3 V  d& s1 I" V- A1 L+ C        addUserInfo(deptVos);% @3 ^; r- m3 T+ I3 _
    }
. P- ^1 H' \8 ]- q  l4 j1 R- l    return deptVos;
9 F' _6 [& @4 }' U}
7 e! d/ {. |( u9 j' ]1 @2 x* J</code></pre>
4 Z+ Y( X) o$ n. c<p>补充附加信息</p>
9 ^8 {0 [# L8 E+ g# S<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
% M7 x( e' g  V; B    // 准备deptId方便批量查询用户信息" V' |+ I, l- i- `  L  ^
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
' C1 x0 [. q7 L& K; c1 {; `, p    // 用批量deptId查询用户信息$ Z' s4 a9 {9 c% b7 O# A0 o
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));" H" W& W/ P, N6 g
    // 重点:将用户按照deptId分组
3 d2 z& X: _/ l& t, X2 C    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
3 Q; R% |! j8 X; Y( [5 o    // 合并结果,构造Vo,添加集合列表& u0 r5 j1 G, [4 ]/ M
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
# X4 `" S7 j+ [8 g, s! o% X}, G2 [: k1 B4 ]; n- n1 Y' v2 e
</code></pre>$ {$ [& C" Q$ I5 \
<h5 id="2理论分析-4">2、理论分析</h5>
9 Y/ j0 v' _, v9 c3 z! t<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
1 R3 n# n, ?9 y% Q* T$ g  ^/ ?9 }<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>) J/ V) N$ b, i" H# g9 V' p, Y$ o
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
+ o9 l! h3 k0 v& J- I6 {5 q<h5 id="1示例代码-5">1、示例代码</h5>" c5 e0 b( C$ m4 o5 v( w
<pre><code class="language-java">/**! B8 s2 b, c9 w4 _
* 分页查询部门信息(其中一个部门有多个用户)
( U9 S+ u  k9 s% x8 ^: p0 S */
9 r/ O' Q9 Q2 j( Z4 Ypublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
3 [" A" j/ ^! N4 ~- n( x' {/ z) Z    // 按条件查询部门信息  k+ |# O- @6 a
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
) e( N$ m/ j! X3 k    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
* f, r" ]% m# A# g    if (deptVoPage.getRecords().size() &gt; 0) {
' [0 y1 {, ]" l% A, B        addUserInfo(deptVoPage);" x+ c6 R" J) Y9 d
    }
; ]8 s! S- T6 _, N; o    return deptVoPage;4 ^$ r/ F3 [- z  r
}! ?3 t3 y% z" @0 S( a2 ~: K
</code></pre>1 d/ I+ C5 G; `' H2 {8 m1 E
<p>查询补充信息</p>1 c4 i3 p2 ^1 T' c7 [
<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {! r' D9 a9 o! U
    // 准备deptId方便批量查询用户信息% }$ k* G: |/ W# S9 D
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
' d/ Q8 `$ N* M+ v0 z; e    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);* s! b$ F. V& E
    // 用批量deptId查询用户信息% M* v0 e1 [# v% S) q
    List&lt;User&gt; users = userMapper.selectList(wrapper);4 h" c. \) Y. f8 `
    // 重点:将用户按照deptId分组+ T! u- o, Y& ^6 l2 X
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
" ]) d% e. p9 _% K' P& S5 i    // 合并结果,构造Vo,添加集合列表
% x+ i5 E# @7 b2 \' c- @7 ^    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
0 w2 l# l% V& l* J2 }5 B( c. c}# f: L1 u, b/ x# \' n" ^4 L& {
</code></pre>
; z  P. L6 h3 {' t<h5 id="2理论分析-5">2、理论分析</h5>+ d; d( @2 T% u8 s: \  I0 g! p
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
; t) i% i! M3 _2 S* P. F" A. l<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>4 f5 W' w3 W: ~+ i
<h3 id="四多对多查询">四、多对多查询</h3>
, Z5 K9 u* Y4 ^* M" U<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
; \' x& f1 f- W; P7 E<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
& c, N. ~  ^! ^, G. J<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>0 V( `! V  u" \  f
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
- B$ i& K5 {5 d, r: ?7 F0 i6 N<h4 id="一查询单条记录-2">(一)查询单条记录</h4>9 Z% ]9 s: P1 g( C. n8 \
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
1 V* T. M+ w, u; w<h5 id="1示例代码-6">1、示例代码</h5>
: w* `5 q; ]: z4 ^/ L" _<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
4 G* u) v  I* J* h1 l( |1 J    // 通过主键查询学生信息
3 @# f' Y" A; X( |7 i& |# X5 a    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
- M3 X9 G: ~0 y6 r8 z    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
) G7 ]% j" D4 h# u& z+ }    // 查询匹配关系! E  E! r) w' K" e4 W" n
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
( N% O9 v% M9 c, {8 G( H    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
* U: N3 a5 o) s6 ^0 V. O. Y7 t4 x" \3 E    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
) P# [/ P+ S2 t" n* w+ i        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));; U- h; C5 O( K
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
  h. F+ \5 W2 u3 P6 w/ m        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
1 n& S$ f& w; [6 ^+ O" |        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));/ ?! o2 W4 R# b- J
        studentVo.setSubList(subBoList);
9 }: O1 Q& ]* j1 [& S- V. W7 G* T    }7 ?6 [$ B3 F3 x" w4 y) z5 O0 h
    return studentVo;
5 ]# K& x7 `+ x& _}
. l1 k+ i3 t/ p0 R3 F- U</code></pre>
8 G: d6 T2 ~  o( y7 M% R<h5 id="2理论分析-6">2、理论分析</h5>; Z( @5 f: H! n7 d! H
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>9 r7 `9 p" s! Q3 T0 d
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>$ G( @; o+ K3 a3 ~  n' H
<h5 id="1示例代码-7">1、示例代码</h5>! [& I: y: h# X* `9 O; H5 _
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {8 O7 u2 N' v8 k& ?9 q
    // 通过主键查询学生信息. n7 \: v4 Z; M1 O" y
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);, {3 p: }# ]4 J3 p* m0 Q" f
    // 批量查询学生ID( ]' X; ]* X- e9 u% V1 t5 W9 `$ b
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());8 ~- Z$ }0 x: m+ d& A$ N
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);: X" ?1 W7 e: n. e! w
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
0 y3 c4 A( l5 o4 E    // 批量查询课程ID6 N0 S5 V8 w4 J1 n+ U$ g# W
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());' N0 h/ B9 k  `4 ^1 [7 ]+ C/ G! B& d
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {2 Q$ `9 _" w6 y
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
5 [5 k- X7 q" C& q5 f8 K        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));: Y' N  t% E. `4 ]; \; x
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
9 T, q9 \& Q7 \        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));+ b# C' c! i- r
        for (StudentVo studentVo : studentVoList) {% X5 ^$ k& h% _( S& s; l6 S7 U
            // 获取课程列表8 T) c8 N  F6 S+ A, S9 M  k
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));. A$ ^% c  A& B& H) i
            // 填充分数- V$ C' s! {/ O
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));7 S& b* W! {6 G) c0 }0 @
            studentVo.setSubList(list);
5 l5 O' a# `) k9 i/ V6 k# e        }
" S& K- c& R. g! k, e% _; c+ O    }
) U- S: V6 o  F! Q    return studentVoList;
3 c- s4 ]/ B" M}* D9 g4 N# K0 o+ T
</code></pre>- g# ?" G; D1 i7 F/ }& p( s
<h5 id="2理论分析-7">2、理论分析</h5>) V/ n3 w/ b* _0 u  I  e$ Y! R
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
) Z0 `/ P9 w" M/ O+ z<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>. z7 [1 t6 c8 F& a
<h5 id="1示例代码-8">1、示例代码</h5>" m( o4 }4 a* v1 m8 ^/ x
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
5 l- T! V' l* l: b    // 通过主键查询学生信息' _% a+ Q3 c; g  G: b
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
: Z8 d9 Q% \0 Y& L1 U    // 批量查询学生ID" ^$ e- O9 i3 ?# o: F4 r/ O
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
1 C* l$ E. {- h    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);% }) O5 G2 l, Q6 G
    // 通过学生ID查询课程分数3 ?$ F; x- }* j, e, F5 {
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);& @. f, J* w2 |2 k) T0 h1 j' f2 ^
    // 批量查询课程ID
4 E7 y* Z: b6 {# p' U: r    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());$ A9 h2 r4 f' S% D0 K
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
; B; @4 E/ b- V5 U1 w2 Q: o% @/ i7 z        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);! d. a/ W7 i- J+ I6 H
        // 学生ID查询课程ID组1 o) h* p4 R( M6 u8 ?& q8 v
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));8 |/ i! f+ F( T5 A4 X  p
( T( e: ]) H+ a/ H0 G4 K, u, R
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));2 t% n& x$ D- D9 I4 r2 `& Y
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);( n( f- c7 l5 Z; K
        for (StudentVo studentVo : studentVoPage.getRecords()) {
0 ?$ |1 b+ |7 y% H  D% B            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
- c2 Z, ?1 w) `; i( X, Z5 f, J9 p            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));1 _! h+ Q  r3 f# r" A0 U4 B: p
            studentVo.setSubList(list);' J( }' o( ^+ n) t0 t& @3 J0 c0 [
        }" Z! ~1 q% k0 Q$ W
    }
( r3 q8 `6 y8 j+ b* n* k    return studentVoPage;
! }  W" M; H/ K4 T}- R& l: D% q/ B- Y+ ^7 A
</code></pre>/ x; J' _. q3 ?) p4 m4 k7 V" g& q: Z
<h5 id="2理论分析-8">2、理论分析</h5>4 z9 F4 @* }9 a# v
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>3 [& |0 W  G5 b8 J" q! A
<h3 id="五总结与拓展">五、总结与拓展</h3>% J5 ~- U/ V0 ]* p
<h4 id="一总结">(一)总结</h4># H0 A/ c( e' o0 i) `
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
7 @7 p8 J& ?, d3 v( C<ul>
" E8 [! U; O( @  x: b<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
0 N6 i/ n9 u1 z2 B' T7 m$ F<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>9 q9 \- X. s. Z8 p: `
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
/ m% J3 D' d# S& ^& _</ul>6 _3 ?6 j" @' K, D; V
<h4 id="二拓展">(二)拓展</h4>0 g% I, G4 h6 I  v3 A1 h
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
* R  u* v) t: H* X<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
( k7 X6 r3 P/ s* _# t<ul>+ _, |7 W0 ]& a  U( Q
<li>当数据量较大时,仍然具有稳定的查询效率</li>
0 B5 L) e- z: N& m) I$ I</ul>
+ e' ]$ T# f. C6 ^. `6 w<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
5 ^5 B& ?: I5 B, \: t  H4 c: o/ Y9 ]<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p># ?. }& i3 x% Y& j
<ul>+ L$ w5 h# n0 {, i; w% z3 T
<li>与二级缓存配合使用进一步提高查询效率</li>) T* \( Q  V5 p0 u/ M+ b/ C
</ul>, b' ~- v( {7 E( c
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>3 T1 v: |+ D  X% I
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>0 d% n5 T- N/ X  u0 i5 h6 B3 m

: }6 {. ?: O' i, {9 O
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-1-2 14:50 , Processed in 0.066950 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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