飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7587

主题

7675

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-9-18 12:37 , Processed in 0.081456 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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