飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8058

主题

8146

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

1 p$ l6 [+ E+ m* A* k<h3 id="一序言">一、序言</h3>
: t9 K2 o$ o( H<h4 id="一背景内容">(一)背景内容</h4>: D+ i" }# h* b; C. ~5 O
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>  ?* Z3 p* C: e1 S' A
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>1 d# p$ X: P0 m5 U/ H0 ~3 @
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>2 G  T) X8 Z& D+ j
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
+ c" [7 E" J$ M0 S0 d<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
% U/ v  b/ n9 x5 W% e" s$ ]& v<h4 id="二场景说明">(二)场景说明</h4>
& u0 t8 ?, ?  F+ w& C8 L<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
6 j! s) k+ S+ @- ^1 U% v% k6 C, U<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >: B& F& R; n: q+ }
<h4 id="三前期准备">(三)前期准备</h4>/ `  `& f# [' |+ x
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
& o6 B; j! A( q' d( O<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >( v5 C- N' B$ b% ?. `8 P6 c- o) @
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>+ O* B$ O$ h. K
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>8 ~7 y( ?/ m5 t( o! V0 D3 c& X5 u  z
<h3 id="二一对一查询">二、一对一查询</h3>9 f: W; z$ X" O3 R
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
! }0 A& j0 O: h- c9 E' n9 r+ P9 ~<h4 id="一查询单条记录">(一)查询单条记录</h4>$ ~& j2 }6 S- x  Z1 T- }- P6 b5 L9 ^
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
$ c1 B7 Q+ L0 X9 G( G& y<h5 id="1示例代码">1、示例代码</h5>' Y6 R) g& }1 T1 M$ ]
<pre><code class="language-java">/**. N+ T' ?' K+ c( R3 V! F
* 查询单个学生信息(一个学生对应一个部门)
% y4 F2 c$ N# Y4 ^ */+ z. K: A; H4 W$ C1 n
public UserVo getOneUser(Integer userId) {
* S! m& q8 B4 g0 g+ K, k% z( T    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)/ ^( e2 V& M7 H
        .eq(User::getUserId, userId);5 V9 q+ D) K# y9 @, a
    // 先查询用户信息
: o- |9 y8 k4 R+ E    User user = userMapper.selectOne(wrapper);& C% g( G8 C9 F4 o4 G
    // 转化为Vo
8 s. `- X6 u, m1 x' _- p    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
" b- [  F- e# k, X3 U. D    // 从其它表查询信息再封装到Vo
! i- u- D+ p2 {# d, [! W    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);. p& }* u" e8 Z# ]6 g$ c
    return userVo;
; ^3 E, l3 \1 s- ~, l}, t6 @8 A- ~  {# j  D* e. F
</code></pre>; F: r4 a5 Q1 i. p1 b
<p>附属表信息补充</p>
8 A; j% z  Q. f" @<pre><code class="language-java">/**
/ D( a5 K9 ~- l& r6 i; K* I * 补充部门名称信息, h6 a4 Y; \4 ~* F: @! o
*/
: q% E3 S/ P, R- |" Uprivate void addDetpNameInfo(UserVo userVo) {; i0 k& a7 V! T: g/ r! n2 V
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
# _# W9 K+ r) B, t9 A8 K; O/ p        .eq(Dept::getDeptId, userVo.getDeptId());$ l( O8 F- C1 {
    Dept dept = deptMapper.selectOne(wrapper);3 t/ i# t4 N  ^- k
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
% W- U& m$ v* u4 @) u) `}
, e8 k% r$ P2 ]$ E  N; F9 ?</code></pre>
. o/ j" h( H, K5 ^3 e4 ~) n; }<h5 id="2理论分析">2、理论分析</h5>$ G- }7 z, i1 R" B/ A' V, m
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>% V# `1 {' H8 O0 R
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
4 F9 h7 Q' F, [( [$ r3 }<h4 id="二查询多条记录">(二)查询多条记录</h4>/ ?0 T1 b0 G& U, P7 \7 }3 K0 M5 L
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
. `$ p$ t+ I, Y3 o; Q<h5 id="1示例代码-1">1、示例代码</h5>( v+ H9 t# n3 e) g' E2 J7 W2 ]
<pre><code class="language-java">/**' Y% s1 D1 F4 L+ k+ }
* 批量查询学生信息(一个学生对应一个部门)6 F& ^$ E( g6 r, D  n- L
*/+ Y, Q. Q8 z- O- C" @8 ~
public List&lt;UserVo&gt; getUserByList() {* x& ~; u1 s7 W8 Q
    // 先查询用户信息(表现形式为列表)
! d9 ~3 @/ b; ^0 o    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());1 b) X6 g8 d( F0 U' g5 D2 R
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());4 w; U; X0 l) f  o# n0 W4 C
    // 此步骤可以有多个
7 s# c9 K$ P" V' @; N% A) i    addDeptNameInfo(userVos);
/ `( a8 r1 f+ Z    return userVos;
* ]( M5 M3 r/ w0 z}
# {2 G8 k/ k8 ]1 M* A: A* e</code></pre>
7 P' m7 p6 p0 w- S* |% c0 F; W<p>附属信息补充</p>
" B' j& m+ Z% M" c<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {% `* x/ G3 U, h# T) G: M
    // 提取用户userId,方便批量查询9 M& P- z0 K+ p  R
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());" n* A8 B9 A1 k, s1 h# s3 F
    // 根据deptId查询deptName(查询前,先做非空判断)
* G% A$ s5 v/ Z3 f    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));3 [3 L+ e+ |( O3 u5 l+ i
    // 构造映射关系,方便匹配deptId与deptName
* d% a9 M$ I3 u, M' y3 K: M    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
2 c! W# A0 P) j7 k    // 封装Vo,并添加到集合中(关键内容)
4 f9 V- ^( h+ P6 ?& j  `! L    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));$ D4 f8 i9 }. t7 L  t
}
! \, x/ X+ X( |& m</code></pre>6 ]* y: j' D, Z4 V
<h5 id="2理论分析-1">2、理论分析</h5>
- B2 _* L. y; n" D& k<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
/ l- u) m& |% P( w- q: |2 B$ V. f<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
% n+ t7 u- f8 U3 D0 `5 X<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
" r+ Z4 p% n7 X, k0 x, ~<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
  m1 p* a% o9 S: ]) X<h5 id="1示例代码-2">1、示例代码</h5>7 J+ U0 M% j+ J. H3 y; [
<pre><code class="language-java">/**
& Q( x3 d7 I$ p, b# O * 分页查询学生信息(一个学生对应一个部门)" a) C/ \* V( L8 h0 ^* W6 Z$ e  Z
*/
" s+ r, M: ~) m- e6 X/ ppublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
7 @- M- ^8 X% i& r# s    // 先查询用户信息
# b( O, a* ~* `- q' |. Q% j4 t    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());3 T. g5 P6 C. Q& i
    // 初始化Vo
; j+ ~+ T7 e: ?( A( }& i! G+ V3 J. p    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);% B. e- X! X. \% g1 H. \
    if (userVoPage.getRecords().size() &gt; 0) {, ^+ F" ]% j# l- ~. ~
        addDeptNameInfo(userVoPage);
2 [$ P4 E* v7 W+ e9 P% P; ~    }
1 R& ?- {* ]! O    return userVoPage;
+ [4 [: S6 x) }& ^4 v4 Q8 u; L0 r}( m" U) g1 o* V; o/ A; b0 @
</code></pre>- v  }" }8 e9 J4 v0 s
<p>查询补充信息</p>
& q2 J. n8 s/ i+ Z! J<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {% m4 u0 `2 P0 G, n
    // 提取用户userId,方便批量查询4 A  j& F% f; L' u; c
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
; k1 s9 ^( T/ `2 x, @* ?# ?    // 根据deptId查询deptName
& S8 _. t- J9 D- c8 w    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
" v' a% X. x1 `4 l    // 构造映射关系,方便匹配deptId与deptName
' y" n. {- _6 @$ |2 L) ?% x* O    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));' K8 J! T. l1 y" m
    // 将查询补充的信息添加到Vo中
9 b9 `- g+ `2 n( o; K    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));/ l$ _0 L* r$ R6 Y' p4 h
}
) M% m  ]3 y* z' h, s9 ?1 v! v% o</code></pre>- n" S# W& n( U  C' R' ]
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
, M2 j# o; ^  ]. z: t<h5 id="2理论分析-2">2、理论分析</h5>" p" N; N1 v! S
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>* q* z+ h7 ^; K6 h
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
& I# q3 O/ K! {3 J* c5 z<h3 id="三一对多查询">三、一对多查询</h3>5 W0 q1 Z/ H: Z( R  d+ ]
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>& l9 N) t/ g1 u; D
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
$ a, l# J8 N( T, c<h5 id="1示例代码-3">1、示例代码</h5>
5 P5 J7 [! [- {( B6 A- C<pre><code class="language-java">/**5 p0 \% v- k  ~% T" \) I
* 查询单个部门(其中一个部门有多个用户)
1 `+ s% O7 p0 y% W* Z" w */
2 O3 L8 K; L% ?$ ~; q) Jpublic DeptVo getOneDept(Integer deptId) {0 t! {! b# l6 F( A" Y1 x
    // 查询部门基础信息
& o" ?& ~; v0 _( m; r8 y4 r. {    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);* K' I( Q# R5 s$ l7 n( h: x* A
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
& M; x2 J) o. E% a    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);& \3 t0 Q1 I7 V, `( O9 _1 z% Y0 z
    return deptVo;$ ?8 h' D7 z: J/ _
}
, x# l6 T( O7 i2 i</code></pre>
1 r. h0 M- X, C0 ^" W) r<p>补充附加信息</p>
, M+ F7 \: J1 H( O<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
8 v! l: S1 `3 @6 d. B# [3 Q5 @# r    // 根据部门deptId查询学生列表( g5 {4 t: c) w2 r
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
9 B  O" T: R( n. t- c1 Q    List&lt;User&gt; users = userMapper.selectList(wrapper);7 C) w2 b9 y% _7 D. N
    deptVo.setUsers(users);0 q# r6 ]3 D: Q7 C; ]! }
}  v  E& B% Y* _8 X; I" p
</code></pre>0 q% y1 g1 s! @! P  g
<h5 id="2理论分析-3">2、理论分析</h5>
* X+ w0 @3 _' A<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>2 j. M2 j3 s3 a3 q" _2 f7 H" j1 X
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>% z9 q) R) q4 b9 n1 I
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>/ m/ b! G& y- F
<h5 id="1示例代码-4">1、示例代码</h5>
  ~' G$ n; {  A6 G<pre><code class="language-java">/**
- i/ z) U: k1 ]! \( U * 查询多个部门(其中一个部门有多个用户)5 m$ D* H1 L" O% m% e! `
*/8 t9 v, H/ _6 z
public List&lt;DeptVo&gt; getDeptByList() {4 q; \8 z' ?6 h% ^2 z
    // 按条件查询部门信息
! o! y4 b* A  ^7 Z9 R' s/ ?    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
5 X6 k3 F$ r$ Y7 V6 A+ m    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
+ v! A/ @9 p( y! x& e3 {    if (deptVos.size() &gt; 0) {
( n( Q, T: E! R  ]        addUserInfo(deptVos);
" s& F7 ^2 U( z# z& W9 D4 [* r% d    }
$ d( j7 W, {5 G! S% v, w& a& \    return deptVos;
, E' B9 h0 O; Z  Y& W2 R$ T7 K$ D}6 r" _3 l& D' [  b
</code></pre>
) G1 A+ C' H9 u1 [4 q% j4 l<p>补充附加信息</p>
. e  j% ^$ l$ o( P<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
" C2 z& T8 }* C1 o" a7 q  f    // 准备deptId方便批量查询用户信息
% Y9 O" n& Z- i! ?5 R' w  D    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());, c- ?8 d* z& z" `9 r" o
    // 用批量deptId查询用户信息
0 M- D$ w, Y, o7 I& a  r+ c    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));( k- e7 }# v" i0 L# d/ b) E, S
    // 重点:将用户按照deptId分组
" U8 r% k- b9 X* |# X    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));, r) j/ |0 |7 v$ Y# [' W
    // 合并结果,构造Vo,添加集合列表+ O! V% l- Y) ~# {/ e6 g
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
8 g- V& T. j/ e" E}
+ H1 e3 G' Q; ~/ P) q  d: W4 n3 [4 A</code></pre>" A+ a+ n) r8 ?1 O2 y; S9 F, W2 M) g% d
<h5 id="2理论分析-4">2、理论分析</h5>, m0 E3 Z7 m% D
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
& j$ G3 }% h2 @<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>9 ]( S- J. e" X% i1 \" F( w- f
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
. B; W0 p  ]" I  |0 \8 r" P<h5 id="1示例代码-5">1、示例代码</h5>
  \9 e2 _) I, O- H; b8 ]7 y<pre><code class="language-java">/**
# J% ]& k4 A7 w3 t# v * 分页查询部门信息(其中一个部门有多个用户)/ ?. y6 a- b1 l9 T' k: X
*/  H! Q3 }6 Y5 `! Y  s
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
# ~: g+ w7 `1 _    // 按条件查询部门信息
" b+ A; n' s! g, w  j    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());1 u2 K  E; W) ]: V  l# L$ |
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
" r) R2 e# t5 l0 k8 l    if (deptVoPage.getRecords().size() &gt; 0) {
8 Z3 w6 A, L: J% G8 n3 C9 n        addUserInfo(deptVoPage);
+ v' S! h4 j: P$ c, N    }
. S& X) d8 F5 j2 s% l6 ~. l9 c    return deptVoPage;
8 G6 w' k. ?, \* O9 m& p& p- x}
- }3 f: z8 ^; K* R* K</code></pre>6 f0 [2 t9 A' i: x$ q! }! V4 n. O
<p>查询补充信息</p>1 [+ I* A% J  }
<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
) @$ t( U" \$ j, G# f    // 准备deptId方便批量查询用户信息
( ?- |9 j7 J! E, t* S    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
# m# s( i2 N9 o+ j* A1 u    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);! }7 c& ^- U* \4 J7 c2 z, P2 N1 g
    // 用批量deptId查询用户信息
7 ]+ p3 P) M. v5 O' B    List&lt;User&gt; users = userMapper.selectList(wrapper);
8 U: Y5 a! u* W    // 重点:将用户按照deptId分组; E$ `- s" v; r0 E: t" k6 |
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));+ r* U9 n9 H* A4 i  q/ e4 _- X
    // 合并结果,构造Vo,添加集合列表
8 u' S( d, B" g2 H    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));3 A6 K9 s  q- m& ?, j0 t, l
}# y. J6 P  _5 I4 v3 l+ t* J
</code></pre>: E4 D3 l2 U0 J" N9 X" E" o
<h5 id="2理论分析-5">2、理论分析</h5>. b& O0 [) z* |0 W# \, h
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
3 p7 |7 y; V6 m7 K, I; _  [; \3 M5 u<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
3 \7 h& s4 |7 C9 w/ v5 w& }<h3 id="四多对多查询">四、多对多查询</h3>
9 d4 r4 {) t; W' }( P<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
7 W# Q9 q, ]# f<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
! r. J% l. ?* K- U+ G1 N4 V7 L<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
' ]6 W6 O) h( Y<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
! C& R( d1 n5 \" z% e. `' A<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
+ m: R7 r7 a  w: l<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
& o0 J! H. ?& h/ s<h5 id="1示例代码-6">1、示例代码</h5>/ u  K* `, H) Z
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
. M) a6 O- j4 `  D. L% ~    // 通过主键查询学生信息
0 z5 l  k( A9 x  ^3 z; a    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
+ W8 O8 m# ~" s. A    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
: h( I( ]1 z/ y0 @2 U    // 查询匹配关系
1 A, D# g4 t8 H" s; y. ~8 Q    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);0 W# C; J+ G7 p( P3 ]+ n. t) ?
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());& f) J8 J' O, V
    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {5 u8 Q  D" ^1 N+ O) S0 L+ H
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
1 D  F# {  t, c5 d( P; r6 W* i" E        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
2 }' ?# g/ N5 V5 A  c& |        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
4 h0 w, Q' U6 B+ i* ]        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
  G# D5 F9 k2 [6 V/ W        studentVo.setSubList(subBoList);
  X2 ~4 p; N# u# ^1 H    }
8 p$ G2 J: X( M' ~    return studentVo;
; J- h8 V, v2 D* l}( [: n1 z# H) y" G/ ]
</code></pre>5 n! P+ ^" w, w* Q2 Y" V3 d
<h5 id="2理论分析-6">2、理论分析</h5>) c4 V/ b% F) ]" ]9 q1 C
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
# ]$ v" _+ {- {<h4 id="二查询多条记录-2">(二)查询多条记录</h4>7 Y' I" f4 z% a" G1 r6 Z" @
<h5 id="1示例代码-7">1、示例代码</h5>
. f7 @$ `" a# e8 B& f$ y1 S" e0 x: N<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {+ H: r/ @$ s9 F0 B: ?
    // 通过主键查询学生信息; f6 a* I. _8 m: m; \" L$ S
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);) N2 A% ~& t; z# ?1 V3 k3 I) `: i
    // 批量查询学生ID
& q. V3 x. G- x& Z6 P4 M# T! B    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
+ X' a4 C/ _- o$ \    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
* I2 P4 }/ m# I4 l+ w% O    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
0 Y" ]  X7 O. n    // 批量查询课程ID
% F5 U# s1 i; K. |3 q& O    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
. M7 I1 f' f, w& \7 B% L; a  L    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {+ B! o' M* `" X! S
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);: ?+ H5 W  ~. W0 q* \$ o
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
$ B8 S9 ]  b; p; R! O# I9 Y* }& m        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);; W9 r4 z8 e% X6 x7 C! G" I6 x( @
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
1 A+ ^2 x0 w5 ]8 _; W! q& ]5 B4 {        for (StudentVo studentVo : studentVoList) {
6 I( l2 ?$ A$ F3 V% p8 J: Q            // 获取课程列表- S& z7 J! I2 l& |7 [0 T
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
: W; v$ l, w0 G+ J+ V& H            // 填充分数
/ n# y6 A* F' u# O            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
+ r% b5 o6 F5 O! S            studentVo.setSubList(list);
4 {4 s8 J, \3 \' {  b. e7 M% m        }
% e0 e: g8 ^3 b% n1 l8 ]( b- G- R    }% x( t) ]7 c* H3 ^. h& ?* e5 z4 ?$ M, h
    return studentVoList;) B. d, C3 w: Q) s4 `' k, |8 y
}
  c% s0 `" s9 |# F7 o" k</code></pre>
# C" u7 L0 s( H# M) H  a<h5 id="2理论分析-7">2、理论分析</h5>
6 d  r  \6 Q+ C9 V/ T3 K6 o- _<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
7 O% f! ~2 Q7 B" j4 Q) s, D3 }<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>& x6 Q7 r) V; a  N1 h
<h5 id="1示例代码-8">1、示例代码</h5>7 f' g6 t) q' s5 P3 z& b  {) k
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {: K( ~% B9 a+ O; i0 A
    // 通过主键查询学生信息# Y1 |. E& U$ ]) r
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
) R+ X7 J) b$ u( P" A* \/ H    // 批量查询学生ID
% \3 ?( E4 x# N+ z% R2 w- J/ i7 T& ]    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
/ L: t# J1 n) f* s( o  K    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);! J- A7 @# ~4 {$ y8 N( ~6 k
    // 通过学生ID查询课程分数7 f% l) S5 R0 l% c
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);4 N, ]/ m6 A; s9 L9 g  n
    // 批量查询课程ID& U6 `" c) h* H6 m8 t& |
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
' N( L, k; I9 c    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {! I3 u/ W; I& |
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);( y( j1 M- O, S% E, z
        // 学生ID查询课程ID组! r& |- n/ S0 r+ t
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
) X8 q- J* p& ?+ D( Q* ?  A; G" Y) C: [. U/ Q, d1 S- t5 ~
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));8 w; P- w9 f$ e  y* m
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
. Z* [4 r1 u0 U        for (StudentVo studentVo : studentVoPage.getRecords()) {
0 E* q* U, c# o9 ~- ~- `( ^            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
3 m/ M# p, K2 }2 Z# W; N            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));, Q2 l- E! |2 ?0 a* R# W4 R% K: t7 @2 J
            studentVo.setSubList(list);% i/ O0 Z4 S: x, {8 V1 E
        }3 L/ i, _$ `- q: _' D% d/ E1 I) d- I+ a
    }! b. O# m# P6 t# t' k2 D
    return studentVoPage;8 h1 c) W( p- k. W0 a
}: m8 E8 W' ^1 u/ y. z0 ]/ ?
</code></pre>
: x8 d# O# _6 H* x+ b<h5 id="2理论分析-8">2、理论分析</h5>, {! l# k, Z  K% ^6 W
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
. V7 X$ U0 o( R7 }) T<h3 id="五总结与拓展">五、总结与拓展</h3>
* }; z7 A' s! v6 N" _( G- B<h4 id="一总结">(一)总结</h4>
( G' B; C  y2 Y9 L<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>/ x1 ]# j' ~( @$ K4 {
<ul>2 ^! ^+ Z( c4 D! e) {$ i# Q
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>" [( g& x2 a) W/ z4 U
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
8 l6 h$ w  p4 _% T% h<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
7 c4 ~, ]! ?. \! {6 K  Y1 c% R8 X</ul>  O" j. }, Z% M% H5 ^9 H
<h4 id="二拓展">(二)拓展</h4>. R8 v, U1 I% b6 [& z
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
2 @% M/ [. D8 o$ K' l<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>4 k, j! N* ?' S4 F  G
<ul>
2 ^; z5 N2 {- }<li>当数据量较大时,仍然具有稳定的查询效率</li>+ ?% ]* m) a- p. @0 j+ Y% n% T) A
</ul>. {2 o2 f, P/ E! k' w/ d
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
. x: W( a8 p4 C3 [: I8 \<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>8 i* i  L6 K# q
<ul>, z/ P. F5 T, J6 o) a
<li>与二级缓存配合使用进一步提高查询效率</li>: d9 S3 _9 a) y. x. k( t
</ul>
: U" f1 w+ N1 n) B, G, J( A<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>" X3 p5 D+ w9 r# N9 i2 ?0 ^
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>! u5 A- h$ V" I

  W  h) r, r; n/ ^+ s
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-13 15:45 , Processed in 0.067023 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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