飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8044

主题

8132

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

& @: i, e  u" r* m. F
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-10 07:51 , Processed in 0.148694 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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