飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8126

主题

8214

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-26 00:50 , Processed in 0.072713 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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