飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8126

主题

8214

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26708
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
' V( M3 {) O+ t
<h3 id="一序言">一、序言</h3>
+ j7 s7 x: D. b  d( q4 c8 j4 |<h4 id="一背景内容">(一)背景内容</h4>: p. g2 O6 Y" @
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
. S/ }9 ?$ I$ u4 p9 `<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
0 ?3 j1 u# ?! P7 x$ D4 P<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
: y9 s) p8 |) B3 g) h, s<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
" q5 W8 k1 d+ Z0 u3 L<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
2 j; o! V3 D9 ?<h4 id="二场景说明">(二)场景说明</h4>+ }1 W8 M) }4 G4 c  p
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>4 I* ^- w+ @  n* r+ a% b' R5 Z3 x
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
6 Z/ X' l$ {" ~; r# i7 k1 Y1 X! C- D( `<h4 id="三前期准备">(三)前期准备</h4>& d! j  p* K2 a4 G  E* T$ Y) C
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
/ `' i) L) _' ]! b; u6 M4 z8 z<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >9 j2 p) c' g6 \; M! ^
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>) `, f; G+ \: v$ r
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
3 _9 L9 n# i4 K) p! R# j<h3 id="二一对一查询">二、一对一查询</h3>' b! ~' ]: h1 y, N
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>+ `6 K( h2 V5 H$ C5 u7 G
<h4 id="一查询单条记录">(一)查询单条记录</h4>
) o. i$ ], c- t: I% b% y! E<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
* O' h) W( W# \$ B& }3 A) D<h5 id="1示例代码">1、示例代码</h5>
5 `- M: s. p6 d# h; V<pre><code class="language-java">/**) w& B8 G& h2 R$ H8 W: f  N
* 查询单个学生信息(一个学生对应一个部门)2 k1 ]# N8 B9 V% d" y- D
*/8 X- }0 h( i) M/ }
public UserVo getOneUser(Integer userId) {9 B: ~% j& {3 }8 d, s  Z! o
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)9 Y- j& X1 X+ D3 c
        .eq(User::getUserId, userId);
8 f9 [: Y; R+ h% l1 d# u) P    // 先查询用户信息8 N3 ^" S& V2 ]$ y0 f# m
    User user = userMapper.selectOne(wrapper);
$ O; d' j' Z2 b4 o. C- J5 f& I    // 转化为Vo! j5 s1 \7 a+ I# |2 ]3 k. V8 c( d
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
# o' O) P. b# |9 w5 J' p6 G    // 从其它表查询信息再封装到Vo
8 Z1 h6 L# s; s0 [6 z7 W    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);& l8 A% N* G$ E. H- F+ i9 ^
    return userVo;, n4 G; I1 W% a6 l( p9 j
}( [& Q! [; ^# h0 O. J2 k8 V
</code></pre>
" f% Q7 M$ F. H5 y3 D: [<p>附属表信息补充</p>- t( b: G* ]* _, j& ^( L
<pre><code class="language-java">/**
% @7 U& u6 W0 C2 P/ C# V7 ` * 补充部门名称信息- j2 S" ]; ]3 _, H
*/
: \5 I; H; R: W  f/ v2 oprivate void addDetpNameInfo(UserVo userVo) {
/ @5 d* }( g7 b; S    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)* d. j9 B5 N* g2 K3 o7 B3 U2 K9 `
        .eq(Dept::getDeptId, userVo.getDeptId());
  f' n+ |7 n8 c! S) a, T: g3 R    Dept dept = deptMapper.selectOne(wrapper);# Q9 i& i, q" K+ |" f! ]6 w, W% i
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
0 k) z( [" g7 \. Z}
0 ^8 x" u7 p2 u' M- E' j</code></pre>
4 O7 v$ x' M/ R, @# Z<h5 id="2理论分析">2、理论分析</h5>
8 k1 Z- x+ ~1 K<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
  s  f; g9 K. Q) P& n" F, T% H<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
/ d% m5 r3 b& Y) I  R<h4 id="二查询多条记录">(二)查询多条记录</h4>
8 E- h3 H3 j/ z2 f<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>% a. A3 q1 s) \2 ]/ ?9 e$ x
<h5 id="1示例代码-1">1、示例代码</h5>
4 U" y& n. v! _! h" T( S: S<pre><code class="language-java">/**9 C8 c1 {- A/ I0 w' K
* 批量查询学生信息(一个学生对应一个部门)( r# u: u9 C3 n& Q+ w! f
*/# G9 y3 W$ g( L$ L, ^. A0 X  `
public List&lt;UserVo&gt; getUserByList() {- h# \- U* t( ?1 S# C' S' R! h
    // 先查询用户信息(表现形式为列表)$ E& w4 H+ F3 B
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
7 Y, b2 S8 H5 x, x" m# m' k; w    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());3 ^6 T3 a6 L  x8 W
    // 此步骤可以有多个" @% }% o0 l6 m3 h7 i3 O$ I0 A) `
    addDeptNameInfo(userVos);
: m/ c: Q  K6 l2 s    return userVos;
: S) C# v! O9 {3 g. K}. h0 ~0 A! s; y
</code></pre>
( e  k9 R+ n3 T! V) N$ K4 b; O/ {<p>附属信息补充</p>2 k1 W+ a( n! i
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {* a/ y$ G1 X: f2 ^6 |% g
    // 提取用户userId,方便批量查询
  h  i0 ]4 d/ W  u  L6 N  d    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
* v1 }, t- t5 @6 C5 U# Q8 ~1 L4 _0 D    // 根据deptId查询deptName(查询前,先做非空判断)
$ n* i  c5 ^# H  h0 S* H7 ]' Q9 x; A    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
3 ]" n. n3 }9 `- ?    // 构造映射关系,方便匹配deptId与deptName
# G- s7 B; t6 A) @    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));2 L% D6 j; F; ^5 Q
    // 封装Vo,并添加到集合中(关键内容)+ ?7 w( }  I: |8 |
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
0 v6 E- ]' ?+ b}
8 ?; l$ g/ m/ ^, G6 I2 q' J; T</code></pre>
6 w  a/ j9 A+ v5 Y) l0 U<h5 id="2理论分析-1">2、理论分析</h5>
1 e* v+ J; M; _. I7 x/ w<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
4 M) s4 s; u$ w; O5 T# W<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
( P0 Y, X  K. A6 @% B<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>/ l  z" u0 q; X% _# c4 R
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
. Z/ r+ N2 A2 R# ]8 y3 [8 L# U4 M<h5 id="1示例代码-2">1、示例代码</h5>" \3 O5 y: {9 [7 w
<pre><code class="language-java">/**( t' H9 t9 a8 W% K
* 分页查询学生信息(一个学生对应一个部门)
6 |& j8 K& V3 E! r, L  e' _ */
0 e; _/ v. S2 opublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
& f* F% R; `$ H; E) ~    // 先查询用户信息
. j" o' M0 G9 P- N% h( v    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
4 T$ B. \0 n4 b! e! |% X% N( B    // 初始化Vo  v% W4 B- c2 C, E+ w- D" _' e/ ^
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
' R$ i" c: w( S& S$ i" }    if (userVoPage.getRecords().size() &gt; 0) {
+ M# z3 T  o; l3 i+ o" M        addDeptNameInfo(userVoPage);
) S, x8 `/ p# G; v7 |    }/ |3 |8 c- U$ Y; Q
    return userVoPage;
# Q& P3 A+ f* p; ~, ]6 Y}
+ t8 R# K% a1 w3 r</code></pre>
9 t$ h+ u: n( Z<p>查询补充信息</p>
9 q; \3 `# w! f0 @2 L, s* e$ S<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {& m- i% M8 ^8 z2 F5 }- p9 C; }
    // 提取用户userId,方便批量查询1 t) l1 a  n" H1 J. w3 f1 ?. r
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
( w- g3 ~5 B7 ~$ U: S, A4 u    // 根据deptId查询deptName
9 L0 F' M  R6 c    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
' E  I3 O# L; V0 W    // 构造映射关系,方便匹配deptId与deptName
9 Z2 i, b- M: O) P. q! u& [6 }    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
, `" Y6 e" Y, \( F+ F+ O! H    // 将查询补充的信息添加到Vo中2 D, L9 s/ h" m/ h) Y
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
9 Q( Y* U9 Z  A1 p) D) g}+ ^4 g& N. s1 o5 _( B! c
</code></pre>
/ I7 d  ]9 O% P<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
6 O, @. T) C4 Z7 S9 m7 R<h5 id="2理论分析-2">2、理论分析</h5>; Y# M. m; m( X# {& j
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
) S' i. v- D! Z; G<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
6 r* [9 T! h4 T: N5 o<h3 id="三一对多查询">三、一对多查询</h3>7 g( O/ O" {3 [% d7 r
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
) [! N2 b- m, y) R% k4 {% \  A<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
0 P4 u. }$ x# x* p5 `<h5 id="1示例代码-3">1、示例代码</h5>0 p8 ^8 z$ y: @/ J$ q
<pre><code class="language-java">/**
+ f2 [/ r2 Y. u+ a" r+ {, @ * 查询单个部门(其中一个部门有多个用户)
: ?) S9 P! T/ a. K) | */) `9 D0 I5 G! D" m$ e
public DeptVo getOneDept(Integer deptId) {. c1 E1 G, C  o: h& j7 Q1 Z9 k
    // 查询部门基础信息
! @9 H* W) V) O5 O/ ^4 ?% ]3 q    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);1 ]0 X7 s* ?3 U5 n/ T/ T! a
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
( x+ E* m* J: b" I4 V( u8 i% ]    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
5 ^* g8 B: \6 ?4 i) {/ c) R- i  P2 D    return deptVo;
* r! u* a# U8 k9 u}: O: f: z; ]0 U% ~: K8 r. x
</code></pre>
1 Y$ X: K+ T6 m) N7 C  j* a<p>补充附加信息</p>
# _/ r6 R) }/ S: z$ \+ i<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {* T0 m- w$ b; g+ g: }' c
    // 根据部门deptId查询学生列表
& |0 ~: S4 ?$ |    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());# }' `: h% q' b0 f. `+ O
    List&lt;User&gt; users = userMapper.selectList(wrapper);
+ y7 Z7 D3 H0 i/ u( x    deptVo.setUsers(users);# J1 C& @1 X+ N6 C8 a
}
* }/ M( Q" x; p3 B</code></pre>
3 T- b) G) ]9 D0 e. h: c1 W. u; ?<h5 id="2理论分析-3">2、理论分析</h5>% [3 L' p" w" _$ t
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>4 Q, K; l' W0 h) C; t7 x
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
! s- y: r0 }- f, Z7 `& l1 |<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
& X% k" `) z. f0 l+ @8 g# Y. l; N<h5 id="1示例代码-4">1、示例代码</h5>) F+ ?9 _9 A& a; r8 @0 B# @
<pre><code class="language-java">/**- }6 N" f$ \) [, A) T* b- V. z
* 查询多个部门(其中一个部门有多个用户)
: h3 h1 b! R6 T */
% b7 a+ z, L' ?6 W1 H( n1 d& Cpublic List&lt;DeptVo&gt; getDeptByList() {) n& C$ F5 W3 z+ @5 l/ H) b3 Z. g
    // 按条件查询部门信息
" `5 n0 Y4 `+ K    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
/ P- F0 }( t$ G, p0 i) x$ r0 T5 A1 ^    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
) t( Y: `, J+ ?    if (deptVos.size() &gt; 0) {
8 @) f2 e% R2 u        addUserInfo(deptVos);, z8 N( l7 i# p' ^2 H
    }; J- P4 T6 ]# Y: `& X2 z1 G
    return deptVos;/ _1 E+ t" {* R) i3 K8 Y/ x
}
6 j! F2 C  {6 A/ a0 k4 K</code></pre>
# ?1 Z5 h- L6 {# r1 u<p>补充附加信息</p>5 Z7 O. s; f  ~$ y2 Y: C
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
* V* x) }& \) K# M1 w    // 准备deptId方便批量查询用户信息
7 d) x* l% Q8 b& j. }5 p    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
' }( n& _! E' u! ~+ S8 Z% w& o    // 用批量deptId查询用户信息
4 ?0 A: W3 V/ \- P    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));2 K. r+ {: d* T0 F2 x/ O. J1 c$ Z
    // 重点:将用户按照deptId分组
; A# _# w8 ?& H. [4 Z0 O    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));* K/ b  K  E1 g# k
    // 合并结果,构造Vo,添加集合列表
* X8 c1 H" U; z2 k    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));$ V: v* t7 i8 f8 E& h, `8 y
}
1 a4 Y" {6 h* N: d0 k</code></pre>0 v0 j. |; t' G8 D  C" c& x
<h5 id="2理论分析-4">2、理论分析</h5>$ b/ A% E( T  p0 t" z1 Y  \- E0 y; E
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
( u* |0 m& \' a+ ]& V! \( K<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
4 {; H1 L+ ]. I, P8 y0 f<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
8 _% X' E. Y/ x0 {, z0 M<h5 id="1示例代码-5">1、示例代码</h5>; ^, _4 N/ f) D8 F
<pre><code class="language-java">/**
' c& j" d4 |5 d& l' [% n * 分页查询部门信息(其中一个部门有多个用户)
7 Q) y! W# x0 o9 H5 i */- o; z. b  Q5 T3 G
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
0 ?* N/ r2 }  O- _" I8 U0 Z    // 按条件查询部门信息$ O( a/ V! K" m
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
5 p+ k- W' a: ~& I; m5 v3 ^    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);, ^. D: ~3 l9 o8 T; p
    if (deptVoPage.getRecords().size() &gt; 0) {
1 p" V$ h% E9 r0 H& n1 F% Z1 m        addUserInfo(deptVoPage);
7 R( w4 W0 _/ e# j    }* @- c6 j3 ~6 o, h  H) x; T
    return deptVoPage;7 a! B. j* }7 l  U
}
  i# ~/ d! V: s+ }</code></pre>; \" i; }7 a% ~: ]" O
<p>查询补充信息</p>9 @- D' |1 P  @# ~' b0 n& g
<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {5 y6 w: s; v+ ^7 p2 V
    // 准备deptId方便批量查询用户信息0 @, P( ?% d6 g# N
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());! H% c8 r" ?2 Q( J. {' S2 v
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
2 T/ T( Z% K/ z' N/ k    // 用批量deptId查询用户信息
% c) J- q) N4 E1 `0 a    List&lt;User&gt; users = userMapper.selectList(wrapper);# x7 ]9 S/ b, ]4 m  m/ `% A0 w, L0 m
    // 重点:将用户按照deptId分组& o9 E/ P0 o5 P# {/ m. a
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));& V  x; v* @! K) `1 q! O
    // 合并结果,构造Vo,添加集合列表
3 h- f9 q" ^9 d+ w# s    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
8 I+ f  y+ M4 a6 {" J9 j4 G}
" g" U3 F3 ~8 y</code></pre>
. u6 A/ O$ P3 }4 j4 E. L. o; |<h5 id="2理论分析-5">2、理论分析</h5>
  ~* j+ @2 d0 b1 z4 T8 M' K( z<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>" d9 ~6 [2 I3 R$ N* T8 _  e
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
6 Z  I' B9 Z& v6 ?, M5 s* U<h3 id="四多对多查询">四、多对多查询</h3>! e/ V3 B) l! {$ s. ^$ A
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
+ ?; M: D' y5 p5 s9 z: a<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
( J" w% F# U' O8 [9 e<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>, c/ E/ z' r7 r+ h  m# \: A
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
  b; `" p' R  h) b<h4 id="一查询单条记录-2">(一)查询单条记录</h4>& ?6 }" Z# D. {  h  ^# d
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
! H9 d  A4 B& i( t; V! z; V<h5 id="1示例代码-6">1、示例代码</h5>) i" Y6 |- P( i. N% t
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {, ]" `- E% O( Y) Z; ]3 Y2 H6 O
    // 通过主键查询学生信息; X6 q* g2 Y5 ]8 h
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
8 L# T! v' Y9 G! I, y3 J, E    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);7 m6 E- T) Z3 @' N
    // 查询匹配关系! ~/ G9 c2 H& M. F% k1 F* D! U2 r
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);; y- Q! K: P. O/ Z3 H# d+ O
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());$ t# D" x  C- K7 B5 [
    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
( v/ H. l  H( ^, a" M; p& n* H        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));; d$ K4 H2 v$ Y6 N% H
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
2 @) T1 ^# f- L6 }8 P        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
" H' s4 f! `* @- T  a% s' k& C        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));$ ]1 r9 a* B  a+ ^+ K+ Y
        studentVo.setSubList(subBoList);
- {9 Z2 c2 L- n" ]    }
- r* X. ]3 T6 S6 z4 F' S+ ?% e    return studentVo;; H# b# w, p! L# P# T
}
+ L' \3 |5 P  c6 x& Q! S0 v</code></pre>
8 E" i( B" ~; s3 b. ?8 G2 T<h5 id="2理论分析-6">2、理论分析</h5>5 e: S: W# R1 _( y+ _+ z
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
& f) s5 |- P3 u# I<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
! {  t( D- m% T  U8 U" D<h5 id="1示例代码-7">1、示例代码</h5>
  U! M' B# v! f! p3 n<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
- ]. ^9 D- y. ^8 P# Z0 @4 V  |    // 通过主键查询学生信息3 B8 T8 f$ B. W7 z# g( B
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);: ]  L+ [! a$ N( K. `, ~; M2 @
    // 批量查询学生ID& C. ?2 H! r' j3 ~, p- ?8 q* u3 \
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
7 z' D" Z& c9 q7 P    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);& F! e, j9 c; Y! o
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
( V# L% o5 t1 n+ k    // 批量查询课程ID
; e: q0 A* l9 \8 P8 L2 ?    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
6 I1 j) o2 M( h" C. b+ H    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
% o- G3 i! I' y& c( J        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);! D& N0 `5 k; ^# M
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
# ^) b% s' p8 {5 ~        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
* C' R: j* I. ^8 h$ h2 g" A8 F        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));+ S/ d' {5 _  z0 a+ r. p& [; J. f7 e7 v
        for (StudentVo studentVo : studentVoList) {! v) \2 C$ s7 v1 |+ C
            // 获取课程列表' o$ X, m  Q% G2 c4 ~5 w3 X
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));) v: E6 D; h. d8 z9 h$ b
            // 填充分数& V" s$ V0 T  k
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
% _' n! k2 O6 Q0 G& Y            studentVo.setSubList(list);- F& @' H- ~/ i2 B0 a. }6 o
        }' R& h. I, X5 ~5 Q
    }4 u' v& K$ N1 u
    return studentVoList;7 z1 T- C! J+ X4 U- ]9 p
}
  m9 l( ~- n) k3 u</code></pre>; p" G8 |: L( S0 `3 }1 Q5 Z9 j
<h5 id="2理论分析-7">2、理论分析</h5>
+ k6 C7 L/ p" y<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>+ P6 F+ P4 w0 S  ~/ p
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
4 z% z9 U. P; Y8 P; o$ u<h5 id="1示例代码-8">1、示例代码</h5>: g; F! i' d! o) u! L# L9 [) e
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
# _/ g7 j2 ^4 v! U4 H9 P. T. R    // 通过主键查询学生信息
- @7 h2 Z6 a, @$ Z. t3 [1 N. K    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
; u: i. }' i( K2 [6 O    // 批量查询学生ID$ u/ U, D7 i9 d# S9 R8 f
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
6 T1 P- Y/ h7 H; m! v8 ]9 G* r    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
7 ]! ?+ h$ M( V    // 通过学生ID查询课程分数
9 F) Y+ U0 C3 Q0 M# `' m/ B    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);5 v; F" M' M+ i9 P
    // 批量查询课程ID# R2 ~' I! `9 u$ ~
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());. q  S, ~' R5 {! A! O
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {# A+ x  u4 U& }* Z: h
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
. g" A, c4 A3 j& K% F" q. g        // 学生ID查询课程ID组# h3 S: A0 v7 y0 m8 d) I
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));" c  C7 T; L2 f( X$ ?5 b5 ?
+ ]' T1 c. t, }( u( R( T
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));( c+ X# q- w- X" l" L& Q( g' y2 G6 x
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);. E  Z) ]) W9 z) q7 \8 A0 |
        for (StudentVo studentVo : studentVoPage.getRecords()) {
- L3 k5 _- Y2 Q4 ~" a3 x- }            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
: B3 n: @7 m+ v( G/ [            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
0 O1 G6 D+ d" D- a6 |& e7 m- a6 b            studentVo.setSubList(list);4 ~. ~% J9 i, W; h9 {! V( P; c0 ]
        }
8 o7 @) y0 C. ]# n# O    }1 q" a/ N% @" |2 N) W1 Z
    return studentVoPage;
- t6 y1 N( M$ f/ F/ P9 t}
: \' P- x5 O4 R/ q</code></pre>: \) j* A  o/ e1 N7 N
<h5 id="2理论分析-8">2、理论分析</h5>* F' Z( H- R, L1 {  j2 e2 X/ u
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
5 X+ ~& b# T9 \<h3 id="五总结与拓展">五、总结与拓展</h3>8 ^& j0 s( T, [0 y1 n
<h4 id="一总结">(一)总结</h4>% x% B' }$ B; E! n1 a
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>' f9 x; c3 P) Q) r. ?/ v, a0 S) k5 @
<ul>
( S( L. G2 N+ Y* o+ M<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>" e- K* m9 N+ w" R
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
  A# k: Q8 c. \* n6 d<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>4 C- z2 c# ^" H! l& Q6 P  H  V/ K
</ul>
+ n8 ], m0 c) ~$ f) F$ c<h4 id="二拓展">(二)拓展</h4>
& l  h3 \9 S6 v4 O8 `! f5 O<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p># I: |# G# X2 x. p
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
- _# `# y6 q& p/ B4 X2 W<ul>
; _/ A" r* r; D7 [<li>当数据量较大时,仍然具有稳定的查询效率</li>* B0 k8 V+ r: }/ t2 B' |
</ul>" C- e: l/ V8 I- n! }
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
5 X0 o' p/ Y2 T<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
/ Q0 ]) j9 C0 D; W<ul>
) r. O7 o. I# Q" d& ]" g( Y) U5 n8 h<li>与二级缓存配合使用进一步提高查询效率</li>
. _  i) s* w# P" W</ul>
6 r" ~5 B$ W5 o; A. v: ~: r<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>& o0 e& K- b, c$ j( I
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>3 w3 d" I3 ^* ?; o  U/ b) i% o

: N  Q1 M5 r" n* v. U! O
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-25 17:00 , Processed in 0.072740 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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