飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7556

主题

7644

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

! U) p* Q) f; b3 T- n# \  P8 K
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-9-13 23:11 , Processed in 0.070795 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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