飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8237

主题

8325

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
27041
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
3 v  v3 E8 ~" p6 X* c
<h3 id="一序言">一、序言</h3>9 P, u' b/ W' y* q: r
<h4 id="一背景内容">(一)背景内容</h4>0 {7 }! v1 a' V, i
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
" K  @% B0 w/ z% O0 T3 h5 t<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
: T3 }$ u/ G# P+ \<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p># X* Y1 [7 H, `( ^4 r
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
0 R* U# w" O9 ?4 x7 ~5 H<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
: j' l/ e+ S2 {8 \" L. }<h4 id="二场景说明">(二)场景说明</h4>, c. R% G8 V# j& i" f" q* x
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
; q8 B& Q2 l  B<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >- }- _0 ~7 n; R) ~
<h4 id="三前期准备">(三)前期准备</h4>
7 N5 z& Q! }) {. \1 X9 n1 m* Q<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>7 ^9 t/ G* X- w4 A$ t7 x, B
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
+ {9 P" D. |3 O1 Y. a; C9 ]<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>8 [  J6 l% l  v3 H& B5 e+ F. h8 Z
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
9 T  ^4 Z$ O) N: J* S<h3 id="二一对一查询">二、一对一查询</h3>2 r# U. F# e+ z4 p1 N' Y1 J5 P
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>: O6 K6 i5 T' D1 z: b1 H
<h4 id="一查询单条记录">(一)查询单条记录</h4>6 y  ]* C, f6 l
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
1 {3 t3 x" i8 q, I& _<h5 id="1示例代码">1、示例代码</h5>
! e; Q, o5 ?1 }/ |<pre><code class="language-java">/**
  h+ F( j/ [. A7 L: Z( H * 查询单个学生信息(一个学生对应一个部门)% m7 K( y% l5 A  X2 S$ S9 y4 _3 t
*/3 e0 c: ?% _& z' O' c
public UserVo getOneUser(Integer userId) {& y+ ~+ K7 b3 ], ]) D% M! R4 {
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class), u" U4 P! F9 U6 B+ l
        .eq(User::getUserId, userId);
  z, w; o8 O: |- d% Q3 C( U0 K    // 先查询用户信息
+ A: v% B" u& e6 Q" b! H7 j    User user = userMapper.selectOne(wrapper);
" \0 [  ]; S6 O4 x( r    // 转化为Vo" [+ ~/ g. s. m/ o; S8 Y; m0 A+ e
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);! ?2 ^+ j9 }( v* s& ~! {" U3 N
    // 从其它表查询信息再封装到Vo
* K: Q! c4 H- Z* `8 r6 Z    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
  ^) {: ~; a2 E% K    return userVo;' h' Q2 ^# N  f
}
8 T7 t% m- R4 H6 @. W8 K</code></pre>1 P# _1 S) U4 J+ [5 I+ C, S: ^
<p>附属表信息补充</p>2 k7 ^& [* t" P* {- e7 T
<pre><code class="language-java">/**
0 E& i  V' x- y' Z- G * 补充部门名称信息9 _5 a1 e$ H% g
*/7 E6 R, G+ N* K& r# {- `
private void addDetpNameInfo(UserVo userVo) {2 Q2 U0 P- |$ B# ^2 F; ~' J; }( s9 O
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
1 n0 n' f6 E7 s  n, r        .eq(Dept::getDeptId, userVo.getDeptId());& w3 }. k9 u2 s' b- U
    Dept dept = deptMapper.selectOne(wrapper);
$ R% U) X+ {& I/ ]6 }" [    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));: r& ~5 I( R% P' g+ ~7 j3 R
}
- @* ~. T4 N0 M</code></pre>6 q  \, y: B) c" J% a
<h5 id="2理论分析">2、理论分析</h5>/ e- E" D1 z! g' V
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
# r. K$ `2 u/ T* S! ^; {3 B<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>1 m* b; _0 x  w; r
<h4 id="二查询多条记录">(二)查询多条记录</h4>3 h5 _! P: s# V! K4 w
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
4 p( B, f+ z# l; _<h5 id="1示例代码-1">1、示例代码</h5>  V6 M5 j9 D; K0 ~3 S; b
<pre><code class="language-java">/**
4 D3 H; U3 r1 X- N( g2 c * 批量查询学生信息(一个学生对应一个部门); D" a7 r# q) m$ ?+ ^. ]8 k
*/
0 z, J. p" {) a' gpublic List&lt;UserVo&gt; getUserByList() {
" E& g9 e" Z, O, L6 g+ D3 ^  y    // 先查询用户信息(表现形式为列表)2 Y* h7 `7 ]5 j) x7 w
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
# I' u* j5 Z- D* T4 ]# P! ?7 Q& c1 O    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
, h9 `. y  Q" e( N3 z    // 此步骤可以有多个$ p! d  d# A- C
    addDeptNameInfo(userVos);3 V. y5 \6 p, `: W
    return userVos;
0 ?& A( I1 w/ N( ?9 E}
9 r% j0 C$ J9 [</code></pre>9 G5 [- T& S, B7 P1 D
<p>附属信息补充</p>6 t5 L* B- j0 u- B. D
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {" U. E5 p" ]$ g+ L& P% X
    // 提取用户userId,方便批量查询
$ D8 F* C6 N! M' h( e) t    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
! e' c% s6 O' a3 j/ ^; [% B  A; N: H    // 根据deptId查询deptName(查询前,先做非空判断)( b, }# F, w. I5 s4 Z# [. r
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
. h- ~  X+ A0 ?& k( k% L    // 构造映射关系,方便匹配deptId与deptName* L6 w* I7 j7 |3 z
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
: ]0 s* x+ j9 o+ l4 B: @    // 封装Vo,并添加到集合中(关键内容), g* E8 Y" [3 H9 j' ?4 ?6 K
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
" ^+ o$ N- V" |4 I}
4 u% @$ o1 g; a; }- |: Y! Q& N</code></pre>& ?' m6 l4 q0 t1 k$ p% I! J9 X1 v
<h5 id="2理论分析-1">2、理论分析</h5>
+ |3 M7 H, B, x8 i$ a<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>' h/ g& q1 [' N. r& s: C1 ~4 i
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>; @7 A8 N: B2 p4 L
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>. Q8 r  e/ J; e+ _  O+ ]
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
+ @! m& H9 f' D! d  g* o$ X" I, W<h5 id="1示例代码-2">1、示例代码</h5>: w2 ?9 {& l$ D' w, W
<pre><code class="language-java">/**
, `! ~* r& @6 F6 S$ C; I; u * 分页查询学生信息(一个学生对应一个部门): d$ ~* `& E3 O
*/0 S5 p2 x& S# f$ w$ M9 O: J" u! H
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
& [* H9 D- v& \- D- B. Q" m* {    // 先查询用户信息
5 d, O- a5 `1 B  k/ W& f8 B! _2 J    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
/ T2 l. k: v$ `0 Y+ j; N  g    // 初始化Vo2 m- B6 q. X) t! E5 Y) K
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
  ~4 _2 _# d$ q* N6 z  I    if (userVoPage.getRecords().size() &gt; 0) {, q" i3 v5 |- J8 ?3 u# W: R, X/ X; R
        addDeptNameInfo(userVoPage);) u4 o: T. B9 F' Z  c5 }
    }
9 A# a9 h) I) I/ D$ L' W    return userVoPage;
% Q6 F1 {) p  Q, F0 U' |4 N0 `8 _}
1 N5 T  ]9 n- e, w3 [</code></pre># W* _' {, t* y: T
<p>查询补充信息</p>
# L& s9 O2 x4 |<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {+ Z: S- p% d. Q# }1 O* Y2 V
    // 提取用户userId,方便批量查询
% ?5 t7 ?3 _, F' e5 N6 s. V8 O' c; Q    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
  C# c5 V8 G5 ?. e( |6 q8 t    // 根据deptId查询deptName
/ l" ^& O! r8 l0 y% `$ n+ \    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
) R( y6 L: ^& w% ~! J    // 构造映射关系,方便匹配deptId与deptName
/ S  d% q8 `1 `3 T    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));2 [! ?# @9 W7 o4 c* Z  U
    // 将查询补充的信息添加到Vo中
( B: K, b# G7 ^1 G. h" F( a1 k    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));. G  R7 m. d3 S3 i6 u, d
}9 s3 d4 |* M$ H$ ]" ?4 B5 G/ e0 @
</code></pre># ]0 D2 a" m: L( t) z
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>' C. Y6 e6 n) B: s
<h5 id="2理论分析-2">2、理论分析</h5>8 Y3 u, |6 i9 _
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
6 R4 v% R) d( d# y% D<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
# n' O/ Y% h' s9 G  m, o<h3 id="三一对多查询">三、一对多查询</h3>
- y( A$ m& s) ^<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>  s4 W; G, s% \, {* @) x
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>- z- l# x% D- ^
<h5 id="1示例代码-3">1、示例代码</h5>
+ A6 t" \, X! A( A5 y6 |) f" w<pre><code class="language-java">/**0 ]; g$ Q; A, M" ]6 R8 ^
* 查询单个部门(其中一个部门有多个用户)
" K; J0 W* ^, m! w/ }# q- X* _* s */! k& H: }0 Z: K" P2 X2 d* F
public DeptVo getOneDept(Integer deptId) {
/ ^$ ?: D; H5 `' B+ ^6 k' r7 l    // 查询部门基础信息: I. p6 k- Z6 _/ {- T5 [, ~
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
: ]/ z3 l+ z( i. d& l& X( ^; C    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
1 [8 b- P. p8 A  n9 x' U+ u5 M% R    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);. \3 l7 q% y- b7 M) u" E: H: R
    return deptVo;
( ~2 }, T* D  \, R, {}- g' @6 N% w( R
</code></pre>
$ G$ B1 J& a, \7 z7 p<p>补充附加信息</p>+ b/ k/ ~# i# z! ~. E, H2 B
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {! Q# o, r: M8 A, t! H* b& K
    // 根据部门deptId查询学生列表; M$ K* T4 l( y0 H
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());* H5 F2 O! z4 @3 Z1 c1 g, [" {# ]
    List&lt;User&gt; users = userMapper.selectList(wrapper);6 y# f9 G9 _" y& N" d- w
    deptVo.setUsers(users);7 T& u  Y; i7 Z+ K5 C
}
  K6 G& K) M4 n6 Y</code></pre>
% K! ?, v' u- f" K8 m0 i" G<h5 id="2理论分析-3">2、理论分析</h5>
  T( Q/ _, U: X9 r) O/ e  ~<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
* g/ M' [3 c' \<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>3 N' T0 V$ l! n2 F+ ^
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
! L5 a9 M' u- w6 R$ h' |! ]<h5 id="1示例代码-4">1、示例代码</h5>
, r5 I  o* p4 j5 f2 a7 k<pre><code class="language-java">/**% C; K# O0 I* ~$ ]1 q& x. U
* 查询多个部门(其中一个部门有多个用户)% ?3 M3 b0 L( W2 h2 [" F( j
*/' t+ n! D9 }1 e" h
public List&lt;DeptVo&gt; getDeptByList() {
" w5 ]. p" E6 ~# E) b    // 按条件查询部门信息1 \9 z  z. q4 V% Y1 ]7 D4 H( X
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());2 L! F. ?3 I: W4 \9 L2 Q9 d  ?; W. M2 c
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());( f# p. `( o, n! n  N" A
    if (deptVos.size() &gt; 0) {4 w( D" F4 b5 Y9 x5 V% B& `
        addUserInfo(deptVos);& e- \* Z, p0 `' y7 C; s, F3 R" r
    }
+ m3 _& v; F2 \5 u# J- V  J* w# u    return deptVos;2 M1 o# J) @8 ?7 e
}
) y6 Y5 C: _$ i# u4 q</code></pre>  G! s- ]. v3 Q
<p>补充附加信息</p>
1 r$ p/ J* {% b+ r<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {3 V$ J7 ]8 Z# W6 r/ I" S4 s
    // 准备deptId方便批量查询用户信息
1 k3 l5 C) d5 y8 d, u    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
3 T  ^3 a% f% z% v  I) S0 Y    // 用批量deptId查询用户信息: b' o8 U( }. p
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));, ?; h6 u- [% \/ q9 P7 S' X1 p
    // 重点:将用户按照deptId分组
' _( {  `6 `  H1 h    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
+ F: v3 H0 _% ]6 U" I8 c    // 合并结果,构造Vo,添加集合列表
/ j& H. y" @8 \- o0 n( F% D4 z+ G    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
8 V5 A7 w8 A, i$ z  \4 `" ?}
6 I" J2 v7 p; f; d</code></pre>0 {1 G; g6 V$ a! G$ i5 d, ~/ E
<h5 id="2理论分析-4">2、理论分析</h5>! w+ u  ~# l# F( g4 y. i' o
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
4 v. D' w7 R3 G4 s1 `; G! ?<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>, l$ o' D( L4 A, D8 O
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
) v1 K) A$ o/ K- k2 M* s<h5 id="1示例代码-5">1、示例代码</h5>
# p0 ~7 f' l4 h<pre><code class="language-java">/**
% |4 `/ N* c0 k9 P8 o' g * 分页查询部门信息(其中一个部门有多个用户)+ T% t, n$ k6 t: E: n8 n
*/
- p8 b8 U' F0 }7 @$ r  H! k. Bpublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {# @+ U' k: C/ y# L  w6 W
    // 按条件查询部门信息8 p$ h' I" o8 u' O9 G4 Y$ m
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());1 e0 i8 C' u& c* X# l: t  N
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
' P9 X( S' x" a1 z# G4 I; J5 d    if (deptVoPage.getRecords().size() &gt; 0) {
. V, O4 k8 l( E# q( ?) z+ T        addUserInfo(deptVoPage);
6 n9 ^% Q$ D/ @, W; G$ T' ^% H* L    }
2 |! o3 `# k2 B7 S! e" m    return deptVoPage;
* N& w9 t9 {( N) h  g$ m}0 g% D- b  B+ W* r; ]6 J
</code></pre>
/ C1 a$ w: l" \8 p6 Q0 y# M<p>查询补充信息</p>' T4 F7 X+ u4 I/ t+ B
<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {4 H; g' ~- H6 I$ I- v' i
    // 准备deptId方便批量查询用户信息
- d7 Q+ z; d% F5 l- a    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
  r7 h! C; X$ \9 k" F, ]    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);# w) ]7 h4 K5 a
    // 用批量deptId查询用户信息
* P1 U! r5 C! c% Z, E6 m    List&lt;User&gt; users = userMapper.selectList(wrapper);
$ \( j, }. z  t1 s) D- h    // 重点:将用户按照deptId分组& {( H. R) T7 J' `1 U; t
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));( z5 Y9 D* u7 \+ y" Q/ U$ {
    // 合并结果,构造Vo,添加集合列表
; Z3 V+ X( ?4 ?/ C  q- J* q. a0 S    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
  H2 O6 U& R) e}
4 c/ h+ i. b, ?  m: L</code></pre>% f: h$ L( V8 R
<h5 id="2理论分析-5">2、理论分析</h5>
. P3 j* M8 B) g9 ^1 C4 v<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p># [9 W! Q) J4 z% p
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
" g/ }+ C8 k1 O9 p2 ?6 Q% N: d<h3 id="四多对多查询">四、多对多查询</h3>% A/ I, Q! Q4 L: B6 m
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>* J5 H+ j( R+ q, M
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>3 K  v& g5 [/ O  J3 N" b  s7 p& B
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
- V1 \4 l& e& f: @6 h<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >. z, K) t/ D  x6 O0 J
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>2 I) [: S& d+ h6 a( Z
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>8 N- k: s5 S  t  n6 t
<h5 id="1示例代码-6">1、示例代码</h5>$ S: @( _' G; L4 \5 ~( d8 [* }, R
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
0 K/ T/ }: r2 x/ J; p) I) v+ B    // 通过主键查询学生信息
7 u6 `9 g6 O! j8 W! i+ F    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);# v( S% A% }# V% W1 ?/ ?5 o$ Y  h
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
/ q5 B9 x. q+ ~! @" d    // 查询匹配关系3 `$ U( Q; a$ O9 L8 O
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
0 V+ z5 C- X% ~$ y/ S: m9 c( g% E' T    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
$ v6 x8 w* f2 M7 W5 A    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
- }7 N" f0 _$ n, O0 B        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
& j6 ?9 v) J" I% L3 c9 }7 d0 s* b        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
) ]9 ]$ Q- V% H* a0 ?        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
" \8 L1 V) x% n5 Y7 N6 y8 d: [# M! l# ^        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
1 B5 J3 z6 F) C% A& H( n* G$ ?0 ?        studentVo.setSubList(subBoList);- u8 F& X& q; t5 L: D/ E
    }$ Y  E/ z' H1 _: M
    return studentVo;
7 n6 L& f( l/ p& x# t: }+ T; j}# A- Y4 P5 `, H* P5 C2 Q# I4 q3 F
</code></pre>
/ z/ u; f# @2 r. [8 k* `+ s<h5 id="2理论分析-6">2、理论分析</h5>
/ b$ x3 d9 f! Y% }0 _/ v<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>, |5 y2 u7 P& j3 s- x+ D
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>6 j! n' B: }! F  \
<h5 id="1示例代码-7">1、示例代码</h5>
$ _. M" R9 B- I<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
& k: J# i1 ~% h1 C    // 通过主键查询学生信息
1 G2 D/ R6 L4 v" P. @    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);% h/ g# n5 x# R: U: ?  f
    // 批量查询学生ID0 G  }6 G" D! W5 E0 Y
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
2 I7 E* U% f& \% o( P" {" }    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);3 @' y' N7 v  j. ]# J$ G+ y( e0 F- I
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);. ^' t) T7 }- b
    // 批量查询课程ID
& G$ J/ F. E  ^% V8 m0 h. j/ _/ ?    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());& |; c# o/ C3 J0 V# q$ H, D
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {5 |- N: V1 m$ [7 O- u
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
$ a6 L2 P/ V( c) |        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
' {6 ^! }+ h+ O" f( A        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
, V2 O+ _" q/ p7 v& t5 I. L        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
* B+ q8 r4 X& b( P, ?        for (StudentVo studentVo : studentVoList) {
3 F. x0 B6 B/ `" W) n            // 获取课程列表% F9 a* [9 y: I- g
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));  C/ g# a5 q- _3 C! c# e
            // 填充分数6 f: m; l9 E6 F- l9 m; a' J$ x
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));# a) z+ ?* {" e6 r. I$ I
            studentVo.setSubList(list);
* h1 M: k$ b% T7 w& }        }
! P# b  f. A& z7 f, e3 I$ T) u    }  [! s7 g0 H4 R
    return studentVoList;% I/ O6 C1 @; Z" T! G0 S
}
" A  Q3 C0 t8 O* a4 P</code></pre>7 ]3 }& _6 h2 j! N% D# K: ^
<h5 id="2理论分析-7">2、理论分析</h5>  Z* J& m% h; A) R/ T; ?. I
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
6 F' ?# f" P" w<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
/ E" S( u6 M9 y+ v1 |<h5 id="1示例代码-8">1、示例代码</h5>
0 q7 z, `) l/ K" N# B2 |# G<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
. I1 u* H* A% m0 J0 [    // 通过主键查询学生信息
/ Y. N( q, l: {# |$ U. Y    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);$ l$ I1 l7 r4 ^9 U. V3 x4 {) t
    // 批量查询学生ID+ R# x1 L% j8 Z) Z
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
5 Y# h( q# n/ x7 A+ F1 K" x9 d    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);8 l& I* H* w, B4 k/ {3 b
    // 通过学生ID查询课程分数
. v" l3 _6 I7 _% j% R    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
" h! z6 V  W( _$ N; D  M8 k    // 批量查询课程ID  F* c! \' n" m% c7 {
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
$ `) X5 I/ `- z# X9 x( l% [& r    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
8 e1 \9 @; O2 `/ \& k# L/ Z$ T        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
$ m; K2 w* Y9 x7 }1 ]* K+ x        // 学生ID查询课程ID组
, f6 V: ^: x2 k9 t" H, A        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));! R3 t' F& M' [/ y# f6 A

7 j. M& Q$ i1 [+ K2 g        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
3 a, y: W8 R! L+ u        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
( c4 h0 |! O* r0 j* G  r        for (StudentVo studentVo : studentVoPage.getRecords()) {
- n$ @) ^- ?3 k1 q            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
0 D  `5 y9 s+ _: }# P( _; u9 d            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
* |5 H( Y( b9 _3 ~            studentVo.setSubList(list);
3 H( F# o) o$ D        }
# J, i2 c- `- n  b  T    }
9 X9 G) k- U4 G1 D* C    return studentVoPage;* l" S- K5 u  t
}: Y+ h# X7 u& \. k
</code></pre>
  L% I% A& }- `1 C' S<h5 id="2理论分析-8">2、理论分析</h5>
$ |. L$ p: b5 D. h0 e<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>; k; g' ]& P: q7 @% {2 q
<h3 id="五总结与拓展">五、总结与拓展</h3>& f5 q7 `3 i& a- s
<h4 id="一总结">(一)总结</h4>8 ^# E* Y$ G8 l. a, a5 C, e
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
8 ?1 r* q+ z' |<ul>
* n2 q+ d) y- b1 Q3 t<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>+ \" g& k2 t$ e0 U0 R# b8 z) O* I/ W
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>) R2 l9 \3 g" b: {& ?
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
+ _% j& ]- G0 X) C  p</ul>
$ V  Y  R5 N: l* c- Z$ o# y<h4 id="二拓展">(二)拓展</h4>
1 k# g6 ^; n/ U! @: M% I<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p># i0 U# j1 m; M0 J" N0 v8 ]
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
! ~7 {, k  O0 \) Q6 |<ul>, Y/ H" A+ h" l
<li>当数据量较大时,仍然具有稳定的查询效率</li># b1 d" T8 D0 u0 K3 F3 M  m, q% z
</ul>
" W2 C, e9 C% I( Y% `<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>; Q- J; ^8 d+ S& N5 d
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
6 G  a# ?0 c/ {3 X; [<ul>
: d8 `& v% w7 v2 A& Z4 _( K<li>与二级缓存配合使用进一步提高查询效率</li>
( |/ m+ h6 E2 L7 b</ul>  V) Q+ S$ H' u% Q) c7 {
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>* l% ~0 p/ N* m( n9 ~; _1 k  A5 o
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
0 W8 _" d5 O- A$ V
9 q; [! I) s6 A
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-1-10 17:22 , Processed in 0.068140 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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