飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7982

主题

8070

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26276
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式

7 B5 m0 `$ c8 Y, {8 h5 H7 h<h3 id="一序言">一、序言</h3>
+ E2 p9 G5 x4 ]<h4 id="一背景内容">(一)背景内容</h4>
3 a! o& l0 ?# O" v9 W7 z2 i* i4 h<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>3 E" w' h- N& a/ f6 _
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>3 k8 k4 o6 L% b, ?7 L) B' N4 b  X
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
) T" J# n( N+ ~' u% ?. S4 E0 I+ j<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>1 V- d1 L+ l2 a0 A
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
' s& Z2 p, o& f8 c* k8 [<h4 id="二场景说明">(二)场景说明</h4>/ x+ G( r3 ^5 B- A. e
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>3 J- }$ `" g4 s4 g: x( m
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
& j. ]1 H$ l' Z1 h- c9 f% Z' s<h4 id="三前期准备">(三)前期准备</h4>8 j: V$ \% g, X: w1 d% \
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
  n0 a" f8 U) q/ s  n) H5 I2 |8 N<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
, S: M# A& m$ D7 Z<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>3 }' R5 y8 E+ K. c4 c! q3 D
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
+ B, c) K# h; t0 V5 T! c<h3 id="二一对一查询">二、一对一查询</h3>( \: ~8 ?0 i: o' u" D$ K% |" f
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>9 h! r+ }6 Q8 _, V  q
<h4 id="一查询单条记录">(一)查询单条记录</h4>2 ?, @& o6 V1 Z- |! ?3 D: M
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>5 S0 u! D% c! Q
<h5 id="1示例代码">1、示例代码</h5>8 `7 T% P+ N7 ^, J& K, Q
<pre><code class="language-java">/**
/ }# T6 e" e& { * 查询单个学生信息(一个学生对应一个部门)
; m% W) C) k- n5 Q! t# M- I" W  g */
! `/ _8 ~" B! K1 P' K3 i, [7 g$ Bpublic UserVo getOneUser(Integer userId) {
$ w3 N: ^# C7 H. `6 E  Y' v    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)8 a& B5 h/ I- z- B. v! s! U
        .eq(User::getUserId, userId);+ @% a1 R- W( h" R7 @5 ^  e
    // 先查询用户信息/ ^( y0 A" ?7 N
    User user = userMapper.selectOne(wrapper);5 U1 G) u* ?8 Z2 F1 D8 }7 ~/ _" s
    // 转化为Vo& g. f  H, C; O, e/ |. r, h
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
/ M7 _$ f+ K7 n2 n4 V2 Y. H/ z    // 从其它表查询信息再封装到Vo- _: r' \8 b/ i- F
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);4 A6 z' c" r3 ^
    return userVo;& z, d& p; N+ K6 t, r
}( j- S7 v5 {7 h' L4 X0 b! _
</code></pre>4 W: s5 B9 K9 j2 K+ G
<p>附属表信息补充</p>2 P# Y" N% `+ Z: m$ R
<pre><code class="language-java">/**& Z* n% C6 C# R& E+ j# c
* 补充部门名称信息) L5 l6 h, @) v9 j4 d) g7 N
*/! j: C( F& [& S/ c- h; M9 P
private void addDetpNameInfo(UserVo userVo) {
7 I, d$ v, F9 r$ ]! f7 f' E    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
. _9 C/ \/ r1 a% x5 {/ G1 V        .eq(Dept::getDeptId, userVo.getDeptId());" d: F0 F- B1 ~8 }, O: X
    Dept dept = deptMapper.selectOne(wrapper);$ G8 }2 {& ~/ V& f
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
  v- t, H, R2 q4 U9 I( ?! M$ G}
3 k+ v; W  e" G) t</code></pre>9 P! i9 J2 c3 J& B. V) f* K
<h5 id="2理论分析">2、理论分析</h5>( t" a& L& L; v: ~
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>$ ^5 c6 _4 t. a( J3 b
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
+ e, Z0 C  ?8 P7 c<h4 id="二查询多条记录">(二)查询多条记录</h4>3 F( U- F4 O' N9 u2 Q
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
  H" O6 _+ Y4 V! l<h5 id="1示例代码-1">1、示例代码</h5>
0 w1 X& D) z5 ]<pre><code class="language-java">/**1 L' h. O9 I& G  @
* 批量查询学生信息(一个学生对应一个部门)
' W% b% f" B, ]" a */9 m" B9 r4 J, O5 o7 G( X1 d' W, [
public List&lt;UserVo&gt; getUserByList() {
8 e) a, F$ f6 @    // 先查询用户信息(表现形式为列表)
6 O2 D" j" E1 ?    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
& m$ M; h8 U5 j. b$ G! o. y    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());, b3 b4 q# \% N2 a
    // 此步骤可以有多个; z9 B2 [) G- U* `3 s4 o2 T% m
    addDeptNameInfo(userVos);8 i" r0 \% [  C; @# ^. x& W
    return userVos;, Q0 o; I8 E1 x- I( t
}
+ \8 I  Q" h- I/ q' ~4 u/ e3 s  H</code></pre>
& A9 S* m, c, z- Y* j<p>附属信息补充</p>
' \  d( `+ X: n<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {
0 q* {7 \7 t# b; k& P' R    // 提取用户userId,方便批量查询$ u. h* G! a0 J% l
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());, a1 l' D/ h' [2 l
    // 根据deptId查询deptName(查询前,先做非空判断)
* h% ^9 W$ x2 T8 W1 U8 V    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));% k. [- l5 X5 k$ }
    // 构造映射关系,方便匹配deptId与deptName( y# @2 k: P. Y) o/ H1 w
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
' t, N; f) b, K9 x) D    // 封装Vo,并添加到集合中(关键内容)
# B) L& s2 B% b  d% z3 G6 {+ K    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
8 Z* m0 F4 [$ Y; Y) A( z}1 ?6 Y- n: W' H/ N9 U2 m
</code></pre>4 D3 B+ V' |& c9 L  L
<h5 id="2理论分析-1">2、理论分析</h5>, F, @5 K  ?; X/ g+ K
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
, G. G1 u4 g9 Y<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
1 [* e6 Q- h" @: y4 T, d: n( x<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>4 W5 P% D: H3 t
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>$ y% v) |0 {1 N/ @# n& X
<h5 id="1示例代码-2">1、示例代码</h5>( K4 `; _" I+ H/ x; v
<pre><code class="language-java">/**
7 Y# t6 U* R& T3 F$ M3 r5 `6 z  Y3 }+ Q% @9 S * 分页查询学生信息(一个学生对应一个部门)
! F2 ^% z' q* V# F5 l$ R: y */. D8 v' |2 E4 o
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
( f: ~# f; Q- w5 F/ i' s8 k% y    // 先查询用户信息9 i; |6 V( \- L5 f
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
. `( `; n. g; D. m7 B. t$ Y0 k: a    // 初始化Vo
8 f, G5 F% U! o8 e3 Y" l. K1 J: O    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
8 @1 d6 j9 C6 c* o$ F    if (userVoPage.getRecords().size() &gt; 0) {
, J% R1 R& f9 K0 s        addDeptNameInfo(userVoPage);( G/ X5 f. J; _7 c" d% O# G, T/ K
    }: c; w7 r4 u  ]- {; ^
    return userVoPage;% [! ~2 D& R( N) v1 ^3 B5 h
}
/ x5 m: ]3 E8 n( _# N</code></pre>7 Z& e; s; ~/ [7 V. u" ~
<p>查询补充信息</p>4 g. v& A2 o* Z: @. v  E
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
4 i# ^2 T, H- M& }$ `# k! e    // 提取用户userId,方便批量查询2 x5 d8 C" x2 O( L8 ?. X
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());( @3 M- Y) b# F, O
    // 根据deptId查询deptName
8 m2 c( `2 L! P) C$ ~! Q  U    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
3 K! L  c7 G7 A0 k9 C+ P    // 构造映射关系,方便匹配deptId与deptName2 h' v9 ?1 I5 _& }
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
, q# @/ @# `+ J# F+ }4 c# P% L6 _    // 将查询补充的信息添加到Vo中
2 d0 y( ~* n( C7 A/ Y7 f5 j    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
; M6 G# D# o; Q- P$ a( c}9 b/ j: E0 @( G. Z/ T- B
</code></pre>0 h4 H8 ?4 U$ v* Z( f- _
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>1 w- k' e1 {( S4 `5 P
<h5 id="2理论分析-2">2、理论分析</h5>
& V5 Y5 e  o( S. U; d' i( e<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>: B8 x6 A, M7 m& g
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p># s7 h3 g& q/ O: M0 }( k3 C) B2 J
<h3 id="三一对多查询">三、一对多查询</h3>) \5 s+ o( a+ G7 X3 Z" j
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>& [2 ^3 K6 }) ]) O+ ?% Q* r, c
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>- V, K. I, A' n" O% E
<h5 id="1示例代码-3">1、示例代码</h5>/ q4 f# c" @' b1 K0 l
<pre><code class="language-java">/**
6 i" K7 g0 R& W2 b$ ]! D * 查询单个部门(其中一个部门有多个用户)2 D" F4 n* i  \" P* y( k
*/: S# l$ {- j7 I$ L6 p+ `9 |3 u
public DeptVo getOneDept(Integer deptId) {
* R- p8 F/ C* V! w" m7 O    // 查询部门基础信息; c9 [3 B7 `" K9 m5 c
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);* w& x: ^3 `; O7 L* G# M2 h3 ~
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);2 M/ U% t: P  ~6 L
    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
  z- x2 b! D2 `    return deptVo;- _2 t7 Q9 e6 [3 u
}" v0 }& `: l' {/ V* Z- q
</code></pre>
. X. l. N6 B5 A6 D% M<p>补充附加信息</p>( u$ U$ m+ |* z  K, S) V
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
, M/ c5 R" y3 C- c- P1 [# V. h    // 根据部门deptId查询学生列表: R' i/ X7 U0 \& F  i+ b
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
9 J! n& ?& p$ O+ Y/ s' M    List&lt;User&gt; users = userMapper.selectList(wrapper);8 v  ^) n, V+ T
    deptVo.setUsers(users);
' I/ C9 F7 R" _4 ]" x}
+ V; O9 _; M6 w$ L' o, A</code></pre>
8 U3 E: c' d' |. r9 `<h5 id="2理论分析-3">2、理论分析</h5>
& U2 g- R3 [, S# R0 y# t<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
5 @( Q6 i/ }2 ^( @+ a  ^<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
2 h4 E# p' q2 Z3 R9 n<h4 id="二查询多条记录-1">(二)查询多条记录</h4>' b0 Q) h, l8 F* x
<h5 id="1示例代码-4">1、示例代码</h5># \" a  v4 H  \2 i  a- ~
<pre><code class="language-java">/**
3 O% \7 q6 B% u8 ] * 查询多个部门(其中一个部门有多个用户)" g) W" [. ?# C' F; v# C" [
*/5 V) V% j* x1 K3 H( m  h
public List&lt;DeptVo&gt; getDeptByList() {
% ?9 N" }, x3 R. ^% c, P! K    // 按条件查询部门信息4 J" b6 L8 p7 l
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());7 Y$ p+ w3 ~- o7 n& L9 l% B
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());+ ?# G6 r7 W/ h, r4 ]1 x1 x/ [
    if (deptVos.size() &gt; 0) {
, l4 M7 F9 c2 T' L" Y+ v3 t9 c        addUserInfo(deptVos);6 z7 ]: G( r2 |& @% u7 U# @& a8 d$ W
    }7 I. n$ e8 D; H1 u6 n; M
    return deptVos;# T; C4 k* r* E
}
3 J! z8 F3 P; L</code></pre>
8 P' `. L2 U  N: j- e  r& p<p>补充附加信息</p>2 N4 S5 Q* a% I7 T
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
& x& R3 W8 x: _8 J" _+ Y1 w    // 准备deptId方便批量查询用户信息
3 L$ m, v9 {0 N. X    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());2 m+ P8 H0 {! C6 I, [) x8 O) W( x
    // 用批量deptId查询用户信息" x9 O) @' X( O' Q9 P& H! q6 ^
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));+ R1 O/ P4 d+ t0 o. m
    // 重点:将用户按照deptId分组
1 G  e+ E* D% w' I" [    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
: n" e; T# W4 O' h2 Z4 F    // 合并结果,构造Vo,添加集合列表
8 J8 O* t! a! ]/ E    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));$ d$ h/ i" t: a8 N; k
}( V" P( m$ k  O# f. B
</code></pre>% `4 s9 f) h0 y, v
<h5 id="2理论分析-4">2、理论分析</h5>) N" j7 |9 H! \" K! ?
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>2 H: o5 k) _" [. P4 b9 p
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
0 D# K& P7 r* W- O8 H4 t<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>, g8 {7 h; u9 p( t# c* a
<h5 id="1示例代码-5">1、示例代码</h5>1 _" J: Y: M' ?& t
<pre><code class="language-java">/**
9 E- w$ p0 |! B8 l3 D3 h! K$ d  x * 分页查询部门信息(其中一个部门有多个用户)
; ~3 n: {4 y+ @1 D3 h */" }" ^) f" U5 L
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {$ T. T1 E0 m. @, E2 c; \. j
    // 按条件查询部门信息! f6 ]) D( P7 s: D/ O8 y
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
  b" p* t$ M8 L$ {. e* O9 l    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
7 K: {  Z0 |/ [) ^/ j" b$ N    if (deptVoPage.getRecords().size() &gt; 0) {
+ h# {" V2 H* a( Z" s8 Z9 L% {        addUserInfo(deptVoPage);
8 V( w9 }0 N. S1 J& M2 s    }
& k3 N$ D& c/ K1 Q8 N7 Q  A    return deptVoPage;
0 x3 n/ ~; f& I" X, h  }, |: M}/ _2 K% j! y& i9 p
</code></pre>
- p7 u) V- B7 _4 ?2 V<p>查询补充信息</p>
% o, @# T, t4 Z: T. |7 p<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {/ l. x9 _5 I1 [9 X  t, u
    // 准备deptId方便批量查询用户信息* f) c) w$ \' {  s
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
! G9 S8 L) y& d- R    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
3 q, T# h6 H! A% D. N: X    // 用批量deptId查询用户信息7 I% n- Z# u" g/ v  R4 S
    List&lt;User&gt; users = userMapper.selectList(wrapper);9 f6 j# w, a. p. @3 Z3 Y
    // 重点:将用户按照deptId分组
# s5 a$ @( `& L* R' L8 X. j    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));; B" G/ q9 W( o
    // 合并结果,构造Vo,添加集合列表8 h/ M! O* B4 ~- V
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
  x6 R9 i2 P! l4 Y}
* U9 g/ s) @9 y5 E</code></pre>. V: y' A/ X8 W/ P) ^& `
<h5 id="2理论分析-5">2、理论分析</h5>. l0 c$ H( |1 o  ?
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
+ ?8 @5 W8 {  P4 k- A* ?<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
' D8 U: p$ s  C5 _, D1 K<h3 id="四多对多查询">四、多对多查询</h3>! z2 L$ c6 P4 p3 \) E& U
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>* B  |  g$ p2 l! D
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>( q. E* w9 y; a& a
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>/ O$ I9 s& o2 m. R5 C1 m0 _
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >. x2 }- t, o9 ?: K% n2 B
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>  \7 ~* c+ y1 b9 I5 I1 i! |& Q
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
" L- p2 ^% w- `+ X6 D# w, E<h5 id="1示例代码-6">1、示例代码</h5>* b8 J/ ?, U! U7 u/ D
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
5 N! r, E2 C) m    // 通过主键查询学生信息4 r% y7 K* C, I6 r! a- L& ?
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
# i2 ~9 S7 m! Q: U1 ^; ?1 J    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);  s, O& Y2 A  L9 _2 V  V" C
    // 查询匹配关系$ l3 f3 V" n, B& d4 b( X% w
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);! t- s' _+ `2 z  N* }) |: N
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());2 t/ Y" T, a# {+ N
    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {: ?& j) [# O8 q  |) a
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));- d6 Z$ ^, U( l' p
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
* I8 A' }, `$ f" p        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
  C) A% b; w2 b2 t) g        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
/ R( I# @+ I& H- ]! p        studentVo.setSubList(subBoList);# Z3 L/ z* M, @1 G
    }
1 d6 L/ Y$ q# |$ d: J# m    return studentVo;
, K% J/ ?9 Y+ U6 t& D8 R' x* ~}) m! w! j1 Y) S6 e, O
</code></pre>
7 {; A3 {/ w! H$ r9 Z& f<h5 id="2理论分析-6">2、理论分析</h5>, s2 i+ E' e: T, j
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
$ v6 j* \& X# b0 V7 {<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
4 I- L8 g, @# Z<h5 id="1示例代码-7">1、示例代码</h5>) ?8 n! |8 z' ~- O4 o+ Q0 Y
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
9 T) N9 @+ I' T    // 通过主键查询学生信息- S; T2 j$ F+ N- D& k: y, N
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
) u- ~% X- A% [' z    // 批量查询学生ID
$ h9 u6 c. U; a5 f! K4 l    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());3 m% X5 I( U$ r' {
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
: g! t( e# q& m4 _7 m; J: b8 `8 A    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
% L3 V0 ~: ?  e! `0 g6 D    // 批量查询课程ID- W8 X/ K6 |$ r+ O* c
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
; f7 Q9 u, _9 L3 ^7 s    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
6 k' c# Y6 E( y0 U4 ~) x! s" P        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
, k# y4 F" H& D& F, s. j6 e& ~        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
8 D6 O+ A/ j9 q' l% G7 Z        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
( ?3 E1 |+ u" N/ \( \. c        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
$ e# V0 y1 E1 C* x+ m        for (StudentVo studentVo : studentVoList) {9 H9 {, d7 K4 |! [# i) P/ x
            // 获取课程列表
9 j$ L! ?/ [  F$ D* n  f+ l- I' T            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));+ O) o5 \) x. @9 M
            // 填充分数
8 o1 d. R, i" D) U6 k9 {) u' w            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
9 {3 a. j7 t$ [: t4 q4 S. X9 C            studentVo.setSubList(list);" z* v, A. K" }
        }
/ _3 L- @! K: c3 p+ o    }
& _4 Z- r- C+ E  ?5 I) a2 R    return studentVoList;
& @) v( q* a: a3 x" @; ]1 I0 u; ^}: a4 e+ d# R& {. c$ h( s
</code></pre>
: i$ p4 r- ^$ O<h5 id="2理论分析-7">2、理论分析</h5>
$ L) _! x) o0 p/ \<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
! N( g+ w8 \2 `- m<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>+ g, U, J$ A4 g5 a' M6 S/ l
<h5 id="1示例代码-8">1、示例代码</h5>
" ?0 Z; S8 p* z5 G! k* ]0 J0 Q<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {, p5 r7 S! l7 P5 l
    // 通过主键查询学生信息
! Z% w- A- Y* j$ y) y$ \$ z+ S& @    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);2 L" S  w! R' f$ c# _7 Z
    // 批量查询学生ID
, }1 p7 s, C8 F    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());, Y+ F; f0 e2 r- A1 `
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);# ^$ f! s* a2 t- i+ [' y: A5 }
    // 通过学生ID查询课程分数: i  M1 y; d: T  g
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
$ d' t) o$ A# r% d2 ]8 ~3 J    // 批量查询课程ID3 l& v. T" }  y+ N! C
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());/ V- Z# K  Y+ i
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
$ H" y" A/ s" E3 w# N        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);0 w- a8 g9 R' Y" v9 Z
        // 学生ID查询课程ID组. W6 {2 G+ R" q+ `+ }- E! s; e- l
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
9 o9 V, i* j5 W5 g9 `* z8 P2 @
  r: B( b: s3 E; u0 ]( v        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));4 n9 O$ I5 z) ~+ i3 I6 p1 M
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
/ r; ?( q; l9 M' W2 Z        for (StudentVo studentVo : studentVoPage.getRecords()) {
# \1 {3 t6 E. H1 t/ M8 X9 Y            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
: o8 j$ \, M8 _% N7 C            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));0 k  c+ W. M  q3 ^1 K' O* ]! B
            studentVo.setSubList(list);+ g( i# q/ s5 f; j8 D( F( k
        }
) c4 @/ J9 H/ M0 H- ~% s3 X! `, a    }) Y" v( P& |+ m; \" U! m
    return studentVoPage;
0 h8 {, r; _1 ]0 s% c; n}
6 x6 x) q, q% H; c4 ~  a</code></pre>
) e# W% s- |- q) c2 _<h5 id="2理论分析-8">2、理论分析</h5>
2 D" G- c1 K" M0 p# d8 I" s<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>" ]! h# R" |, x, [( b* ~
<h3 id="五总结与拓展">五、总结与拓展</h3>4 ^) q1 J, K) w0 r* i
<h4 id="一总结">(一)总结</h4>
# J& B$ m5 p1 A<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>( s1 Z" u! a% y8 r$ i4 N9 g2 V
<ul>
" T3 [( j! S* l3 ]6 s<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
2 t9 L; \% _  I  P! K8 R" W<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>8 X5 W3 o  e" E/ p$ A" n' w3 M* b
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>1 \' [0 x' Q% ?
</ul>
" T& W  M% f+ q( i% ]* u8 m* t# S. ~<h4 id="二拓展">(二)拓展</h4>& I& X' F( u0 y8 G) p9 Y
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>% @. n  X: u! A  C
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
2 |! Y. I; L: P$ h  r<ul>
+ R4 D; x7 @. J" {: }1 Z# z<li>当数据量较大时,仍然具有稳定的查询效率</li>/ T4 u5 y' A3 D2 a  }
</ul>
" ?( G/ l+ d4 t; j' C  [<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
* L5 R# K- m9 P: ~<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>6 e) l% b+ M1 E) k. e
<ul>0 @' Y( r9 H3 I  L
<li>与二级缓存配合使用进一步提高查询效率</li>; l5 Z+ v) g9 @+ i" r9 N
</ul>
. B2 ^5 d6 L: z5 Q! B9 E) e1 u. M<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
; D( p4 C4 e" G<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>; f7 F7 P5 z# h+ j2 e) f$ ]* ]

  O; T& P' m8 v  {' }: q3 M
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-11-26 22:33 , Processed in 0.071603 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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