飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8115

主题

8203

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

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

# C( P% A2 h4 G/ t
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-21 03:11 , Processed in 0.065415 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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