飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8049

主题

8137

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

( C' v: `- I8 i% Z  ]1 E8 T% V
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-11 06:05 , Processed in 0.106204 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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