飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8059

主题

8147

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26507
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
- ^# q" N  m  y4 W
<h3 id="一序言">一、序言</h3>$ U: Y, x- T! P; A% ?9 x
<h4 id="一背景内容">(一)背景内容</h4>  i) W7 {7 B, @' R
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
, G: g/ C% a# @6 V) Z<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>. D0 s9 q6 C  l: u
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>1 l& F# p; O4 E$ g
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>/ `6 w( A4 U; J
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
3 [: ^, {9 E# b7 G4 B<h4 id="二场景说明">(二)场景说明</h4>
+ H2 T7 v3 T- I; C3 [, c<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>0 G, D5 k! M" ?* e. r; R
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
7 Q" \8 s$ A# P5 j# O9 m<h4 id="三前期准备">(三)前期准备</h4>% c/ j3 Y4 a+ p( h
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>: J* z* ^) Z: F8 y! d5 t0 Y
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
- s" v4 J2 ]- `/ E' E& g" f<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>+ S$ T4 ]9 @5 y; x' Q1 U8 M- k' z
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p># O2 Y6 g/ N6 y4 b, }+ p
<h3 id="二一对一查询">二、一对一查询</h3>8 j& h5 j- b8 Z& X8 |" F# X* b- J
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
+ b) W$ |& I' L4 U<h4 id="一查询单条记录">(一)查询单条记录</h4>, R) P0 w* X' x/ h" z+ p
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>* V) n$ _! q) ~' N' A9 H  c; y1 Y, T% g
<h5 id="1示例代码">1、示例代码</h5>
9 d. R8 h# C5 A# u; f( B<pre><code class="language-java">/**  j: J5 o7 o2 N( B
* 查询单个学生信息(一个学生对应一个部门)
4 k+ j# t7 P" _& N  O */& R9 X$ z$ }, Q6 J# `# d6 |/ ^" W
public UserVo getOneUser(Integer userId) {& a( A7 i2 R; A" p  {$ z7 l9 C
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
9 m& w5 y$ G; Z( a7 O        .eq(User::getUserId, userId);
% H4 X* G3 @: D3 g, y- V  }9 s: p    // 先查询用户信息
7 J' [  m( M9 E4 x+ C    User user = userMapper.selectOne(wrapper);
) l$ K0 k, R! ^  x% `    // 转化为Vo
9 s0 N! ^/ k- F    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
8 s) `' q/ c- [  k  ~    // 从其它表查询信息再封装到Vo1 {. z/ W1 b; D
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);/ n* p0 u8 k5 h( ^2 y
    return userVo;
  k- D. n/ ^1 ]: m/ T}9 S! y& v' `2 d' L. L
</code></pre>/ d# ?6 j4 L; O& Q6 C: A
<p>附属表信息补充</p>, p' o/ z1 v4 ]: T
<pre><code class="language-java">/**
6 H3 M; `3 ?' L) d. _ * 补充部门名称信息
( G+ Q; F' \) y+ _$ H/ C/ F2 c */! J9 G# Y5 V! l2 f2 p( G4 q
private void addDetpNameInfo(UserVo userVo) {
# g( P1 A. |/ V" t    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class). K4 S. f9 R, R$ D- v
        .eq(Dept::getDeptId, userVo.getDeptId());$ N0 w/ F4 j: ^6 r' r
    Dept dept = deptMapper.selectOne(wrapper);
$ o: `4 m; q! c/ L: |- h    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
# X6 U" m5 Y$ S+ y2 w}
8 L1 ?8 f! N* V</code></pre>
9 n! Y7 U2 @) B8 N8 ]6 u/ R<h5 id="2理论分析">2、理论分析</h5>1 r( X0 D0 E3 j/ m6 \3 h: t0 C  H
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
3 c  S% x# ]; j5 ^<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>6 C/ a" K, [7 U9 W3 G' _+ E, P* B
<h4 id="二查询多条记录">(二)查询多条记录</h4>
4 D9 t0 I2 o; p4 m  \& o5 l<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
- Y8 R- j& V1 R6 d9 z9 Y+ k8 W<h5 id="1示例代码-1">1、示例代码</h5>
! B; z. X2 Y  z+ i/ U<pre><code class="language-java">/**: W0 n4 m  c( A6 I( D0 U
* 批量查询学生信息(一个学生对应一个部门)
4 T/ \( Q& E. C2 }3 b */8 ?9 z1 v3 ]0 `5 a3 ~' P: O$ D+ E! u
public List&lt;UserVo&gt; getUserByList() {
+ C+ F8 w% s6 u7 t0 e; m0 V6 \/ d    // 先查询用户信息(表现形式为列表)' p9 X  ?$ W0 u- D: o0 C5 B5 Z0 M
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());/ b) \& B# ?1 F3 f
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());% D4 ^% `% i( y9 q& i( n' Z+ x8 B
    // 此步骤可以有多个/ k* p- b$ j) `+ d8 ?' ~8 Z4 K
    addDeptNameInfo(userVos);8 s# x2 K+ p8 d& k, _  A2 N4 ]% B
    return userVos;
- V3 Q! |8 L3 m) [}1 p5 a" h. T8 n) P: B5 v1 R
</code></pre># @2 i7 b* B4 ]$ g1 z" q+ u0 B
<p>附属信息补充</p>
- E0 Q, a, G# S9 H<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {( V  ~: T6 @$ _; J" a
    // 提取用户userId,方便批量查询; |- [8 V' h' m
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
0 [# y$ V" m, R# `5 B    // 根据deptId查询deptName(查询前,先做非空判断)
2 M% `8 f6 m& z+ }1 p    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
" w7 W2 r6 t0 j9 C1 s    // 构造映射关系,方便匹配deptId与deptName) ^2 X$ ?! h. ?: z3 }6 F
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
+ P( \) E+ N, z2 b    // 封装Vo,并添加到集合中(关键内容)
4 J$ J- ?& ]8 d. M* l    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
! I" |# q% H8 r3 _2 H}- K. T/ |, f0 V
</code></pre>7 u' u' I9 N( ?1 n: ]) a
<h5 id="2理论分析-1">2、理论分析</h5>
4 O( _, ?6 x$ L! v<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>7 Y; l% s6 T( q- x1 X: Y% b
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>: @" c9 S  M+ P0 f7 ^3 o6 T
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>' Z% `, y6 ]+ c& D3 U3 ~% P$ ]) `
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>' E! y" n! ]7 t3 e* q  ~1 D
<h5 id="1示例代码-2">1、示例代码</h5>
  n% y9 t! N+ a" ~6 f<pre><code class="language-java">/**( D- u* M' n( Z: `/ a( i( l7 |  J
* 分页查询学生信息(一个学生对应一个部门)( y" h# h, p" K
*/+ U7 C8 p! v/ d
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {: z: t6 k: l7 {/ X5 ^$ h$ n& j
    // 先查询用户信息# p# x. ~4 B$ N
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());0 E5 A0 I! d1 k
    // 初始化Vo- ~# n5 q* u% |2 A
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
" Y: h& |( b+ T- \) d* ^  J    if (userVoPage.getRecords().size() &gt; 0) {" z  _3 m% @( K7 I. a+ `* m
        addDeptNameInfo(userVoPage);
8 o+ u% p" X8 [3 z6 q: a& v    }
9 ?- _& }# A: e    return userVoPage;# S6 x9 u" K6 u9 E
}- z7 A# o# Q. B" w* ]( s4 B
</code></pre>8 f+ b% L) g& }: k
<p>查询补充信息</p>, J6 v* q1 w- a& e. X9 |
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {5 X( D1 m. ]; f% H; a
    // 提取用户userId,方便批量查询; T. E/ E" F+ w% ]$ I
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());: p* V8 Q" m+ d* b- ~: [" m5 k
    // 根据deptId查询deptName+ \' H% u5 r: j# ~6 y
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
# J2 Y: R8 E+ l! |- Y    // 构造映射关系,方便匹配deptId与deptName+ A" h3 F( w- n/ R7 O9 r9 X8 d, i" a
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));2 @+ O7 r# B5 n; o1 ~1 r
    // 将查询补充的信息添加到Vo中
6 q+ I9 t8 v, g! ~3 D* r$ a& O    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
$ \- \6 w: F8 M6 p5 `: V0 M& H0 J}1 d5 t6 S( H5 K1 i/ h2 b
</code></pre>' p6 ]% s$ V3 y" W: b1 R9 J
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
7 M0 e4 D" P, u+ d) v) T5 j* C<h5 id="2理论分析-2">2、理论分析</h5>2 q* C  H7 Y3 T
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>7 i: u) Y. O# }) F
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
. S' W/ d" S+ U* @7 X! K2 e: }<h3 id="三一对多查询">三、一对多查询</h3>1 w5 \3 r; ]: A, M, y
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
, Y. D! i; g, J8 Y<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
( w' U4 S; k7 U8 x<h5 id="1示例代码-3">1、示例代码</h5>
8 d+ \  f9 L& X& E% y1 e<pre><code class="language-java">/**
( {0 P* C  v3 ~ * 查询单个部门(其中一个部门有多个用户)
; m4 C& b' O. a  J; t" q# W */
+ @+ v: L; ]) ]public DeptVo getOneDept(Integer deptId) {
/ N% P2 z* K3 Q8 I    // 查询部门基础信息1 T! t3 D. G- m$ T
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
+ t/ L5 n+ o1 y3 i    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);8 I+ j7 P, D  z, O5 c
    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);8 N7 x0 E; Q" ?! N9 c8 h
    return deptVo;
5 c1 V: M4 U7 f2 H& B}
! s# j3 K4 [2 T# g</code></pre>
5 T7 F8 t. Y7 {0 g<p>补充附加信息</p>
" h5 Y7 r/ \+ u7 y% A" P" B: y<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
( M/ J4 e9 m: }8 B1 _# V    // 根据部门deptId查询学生列表
$ p( F# m5 [$ y/ g' a. e' C$ [$ R    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());# z  J$ ^8 z  y" n! C1 S
    List&lt;User&gt; users = userMapper.selectList(wrapper);8 H3 `. D  t% K5 v
    deptVo.setUsers(users);6 @( r, m0 v. p) E9 {( n' i
}& [5 h* p! {5 |7 I$ M5 t0 V
</code></pre>
% c' a$ l3 a2 t5 C/ ]<h5 id="2理论分析-3">2、理论分析</h5>. h. H+ V7 ~0 L# }7 K+ ], w* n/ h
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>1 v- \5 ~! Q2 Y
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>1 Q$ b8 [6 p* g! U" Z) w! M
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>& O: W+ x8 H! T6 J+ k& F
<h5 id="1示例代码-4">1、示例代码</h5>& F' }3 ^7 j+ v( o0 v# h1 y
<pre><code class="language-java">/**9 S4 e) P5 L0 j9 _2 y4 N2 P+ c
* 查询多个部门(其中一个部门有多个用户)
; Z8 l& T* r' Z, I */
+ b6 n) C9 M" E: q9 c$ Z# spublic List&lt;DeptVo&gt; getDeptByList() {
1 q2 K( B1 ~0 u& U0 {0 a    // 按条件查询部门信息8 c9 \, r4 p! D5 }* ~
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
5 h/ k) x0 P. T/ N$ _    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());* f& t) _; h+ l
    if (deptVos.size() &gt; 0) {0 J& t0 a* N5 X/ J6 [# @
        addUserInfo(deptVos);6 i+ v0 Y0 [( |+ H; u/ u: C
    }0 s7 `) {7 n" d; a$ a; J
    return deptVos;1 a# F4 _3 o; D- D
}/ m7 u  I& o- P9 x3 u" v
</code></pre>
4 c! {; ^. M' C<p>补充附加信息</p>5 K8 X$ W8 p; L3 y5 Q
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
' O6 K/ C7 a) P, w! f    // 准备deptId方便批量查询用户信息2 Q) W/ \8 B$ N' j7 c
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());9 d& U: u; V% X) _4 d2 W& B
    // 用批量deptId查询用户信息
% k) F& w+ Q1 `" z' H- W    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));# g/ [8 _4 V% K8 l( ?  ^4 I
    // 重点:将用户按照deptId分组
9 a9 B5 r4 |" _9 \2 M* i    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
+ g8 F: p8 B& c4 G    // 合并结果,构造Vo,添加集合列表) c2 w9 s( V1 `, {4 g0 t
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));+ Y6 ]7 S  _, G
}
4 U2 ?8 i$ u+ l; P/ V2 |, {</code></pre>
$ t1 g/ K* V- B+ r1 n' a$ V3 u8 e<h5 id="2理论分析-4">2、理论分析</h5>
% V- l' W/ j5 k) l<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
: {" R3 c% ?1 l; \1 {$ H<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>$ v+ p+ v4 r+ V. s/ R, T4 [' G) {2 @& ~
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
6 d& z/ j2 e+ y- Q. B! k<h5 id="1示例代码-5">1、示例代码</h5>* `- w+ I7 m6 ?$ m9 X7 g
<pre><code class="language-java">/**" R  y+ H8 v! @" q
* 分页查询部门信息(其中一个部门有多个用户)
5 Q0 W5 ]% n7 u. d! x */8 U+ ]3 S; E, N2 i9 V6 ]
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
1 p* [" H, K3 `: l& m- w    // 按条件查询部门信息! u' A! _" b& d
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());8 {2 X; O: g0 a, b' L
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
( q6 n" x: f8 q8 @8 V: b0 l    if (deptVoPage.getRecords().size() &gt; 0) {
+ }& B# l& |5 v' W! v$ L        addUserInfo(deptVoPage);
# ~3 G5 B6 }+ ]  f, {+ e    }
: |. h$ O/ L  B4 B% {    return deptVoPage;
6 {8 y3 w! I9 V}
9 l' ^5 ?/ H; @</code></pre>8 d% ~0 Q( {/ r& `1 v
<p>查询补充信息</p>
" z4 y0 r8 T" ]' d$ ]<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
( p- Q/ C! q# g    // 准备deptId方便批量查询用户信息' I$ N; }: O1 q! y1 U( i
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
# }$ n/ \& o% j$ M    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);$ F" v8 ]+ A- b' K8 E
    // 用批量deptId查询用户信息
3 r' X- x. H3 _# L# `8 G    List&lt;User&gt; users = userMapper.selectList(wrapper);/ I0 Z8 V- e! `
    // 重点:将用户按照deptId分组
. F: H: t! C/ W: e/ }1 C" v    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));7 C! K% ~/ P( ]
    // 合并结果,构造Vo,添加集合列表
+ X0 M3 o, c+ Z/ N; A$ E& v# [; j3 G% W/ V    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));" G" w, N- x0 p3 E$ K, ]1 V7 W8 o0 y
}
6 O, V+ E4 u# M. x</code></pre>( d8 M" q! _( ]. a1 n. h0 G
<h5 id="2理论分析-5">2、理论分析</h5>
" t0 l; B* R, v" }- f<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
6 ~7 p& a- U1 N; q<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>+ G5 D5 {) h& ^2 ?: _7 f
<h3 id="四多对多查询">四、多对多查询</h3>% {  I. k3 E  O7 c  J  W
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>2 H1 e8 W; N3 s$ G( y# _$ C
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
: q+ k/ G; p* i  v3 n<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
; Q" {3 E" Z& e1 V4 T3 v" u* c<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
& r) J: b6 \) \  R7 y<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
3 a! j, V- L7 G- Q<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>" y! F2 h; h' h
<h5 id="1示例代码-6">1、示例代码</h5>
0 M, s  w$ K& o% X) [<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
1 ]2 j( v/ t( v' A" Z) N    // 通过主键查询学生信息
$ e; P. M. |- t- T    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);8 }' M% O/ a' ]/ h6 l# B% K1 [
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);  O8 V( Z" m9 J  x
    // 查询匹配关系; u; \/ X6 @! j) g' e) k
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);" W  ]* T: _  T9 D
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());7 W- a# T, r1 }6 s9 @8 T# Q( N
    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {1 a4 E0 s1 x9 N# d2 ^
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
$ t9 w' g7 X7 ]        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
9 p5 m7 ^0 w  ^; Q+ }        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);0 T2 I! |+ ]/ F6 f* O
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));% \1 t' w  D) f" s, D& L( Q$ q1 L
        studentVo.setSubList(subBoList);2 P* ^* }6 }# m6 B
    }+ Y. `( R/ m; t; _0 L
    return studentVo;
3 G7 i3 F) F! S% A* Q) ~}
4 M9 _! n5 @/ T& C+ J) ?' b</code></pre>
7 H2 j6 ]) |/ C) T4 D, T3 L# E<h5 id="2理论分析-6">2、理论分析</h5>
+ e& ?; D0 @6 F<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>- d; }7 h- h# x7 G4 z3 d
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>6 J+ V  k' t+ O7 @2 Z& z
<h5 id="1示例代码-7">1、示例代码</h5>* b! f6 o* J6 N' d0 {% K' l
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {2 G/ h6 X. r% G( ?! h
    // 通过主键查询学生信息9 \: \/ I! }, p9 ]/ H) ^
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);" q+ |/ c# Q3 Q( {! U. P# ]
    // 批量查询学生ID
2 M$ U+ Z+ b6 x- |8 d    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());" @2 h. o$ D+ s, }8 t
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
( I( S! K, i5 b) y  I    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);0 k7 g$ Y, Y8 G) \( g
    // 批量查询课程ID
6 _0 R0 c: j6 P. o6 V5 [+ J. R+ ^6 ]    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
, N+ O+ |. A9 ]9 k    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
: \# \5 {8 l; I) n$ g        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
  n" P, y5 W6 G9 t% X7 {        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));7 a( f# M! y6 ]# N) \. S  j
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);; Y3 v' Z! @8 @; ~" E
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
% C' p& q9 _$ C( C' n        for (StudentVo studentVo : studentVoList) {5 u: s1 @& W( y8 m$ K" [/ B5 {$ F" z
            // 获取课程列表3 J: l! s0 B7 |* E) U( p
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
) c' N: c) Z. B            // 填充分数
8 N  `9 c5 ]8 o7 P6 T  m" j6 ~- B) w            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
- ?% P% s4 l  e( a3 D# ^* ~            studentVo.setSubList(list);; _7 N. V5 ^8 [$ N4 |  _
        }; R. \0 s, T1 }3 C! R; X& W
    }
: t! Z+ [# N1 s* O& I    return studentVoList;0 f! A5 w$ E6 G# k# |
}) A2 I. n9 C% b1 u1 F8 h, @$ W
</code></pre>2 O% [) C3 h" h9 e( x
<h5 id="2理论分析-7">2、理论分析</h5>
) t& ]. Q4 E8 A1 H% Q& ^- b<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
( |# D$ v- x- U. \* f$ p( ^2 B) z<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>; V$ `3 Z# i( v" G- }/ k0 y, G, [
<h5 id="1示例代码-8">1、示例代码</h5>
+ O1 F' h6 V7 r0 d, B$ u<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {. n& g# H  ?, F0 n* \0 T* p' G# |" q
    // 通过主键查询学生信息& K3 t8 m$ t+ ?3 I  x% g7 s4 _
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
/ P5 _5 d- h/ J+ I- w/ m/ Q, R    // 批量查询学生ID& f3 B7 ~( r) I" c! S; N( T
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
+ P5 d0 r  }5 l8 G2 L    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
* V! u5 U& [3 n3 J2 K# r6 f    // 通过学生ID查询课程分数9 F. `  g! o1 `  u* U, N
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);2 l& ?2 l2 O& r% m% ?/ D2 x
    // 批量查询课程ID/ O% G0 r" Z9 W+ f
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());% h5 c7 M/ @5 H$ t
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
) d( L- X6 d% c6 w  ~: t" ]        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);: Y! h0 c/ S! u- H. Q( _
        // 学生ID查询课程ID组" u# x. |3 w8 F1 ^
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
2 N$ k3 H1 I' l3 W- q$ X
; f5 T  _8 I, @8 T' O1 }) B        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));4 U7 B( v& M) X' P, K  p8 W/ w# B
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);9 Y2 t5 G% t1 ]2 E5 J% k
        for (StudentVo studentVo : studentVoPage.getRecords()) {
, w3 U9 B+ f# g* P. W            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
, l5 W! K/ G. ~" S9 l9 F: Z" R) @            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
+ \9 P) O0 h+ Z            studentVo.setSubList(list);
- t) X% ?/ _( n7 w2 O        }' r/ M% ?6 i& n( x$ G7 J
    }; Y  r/ ?( b, C) J9 M
    return studentVoPage;
% S) l9 ^: U$ d$ ^5 i9 F1 q}
( ~# x$ `# F' L</code></pre>
+ E- z: c* x" R& r<h5 id="2理论分析-8">2、理论分析</h5>
, K$ {' C7 ?1 I<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
* ]3 Y: }: B' u+ Q( j" @<h3 id="五总结与拓展">五、总结与拓展</h3>" n* n3 Q4 ]+ K5 ^+ r3 Q8 K
<h4 id="一总结">(一)总结</h4>/ T7 c- x" x8 R, d# K
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>+ f" L% n0 O8 j2 l& g" J! Y
<ul>
, s" L; G8 W, Y4 k( t<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>4 ]5 ?) a: V# d& n
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>6 Y+ X3 ?3 t- p4 b% `$ s( e0 k
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>- K$ }1 e( B- R. n
</ul>
; G' v* X* y' y) s; @1 e. n<h4 id="二拓展">(二)拓展</h4>+ ?& h: J9 ^* x' M" z
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
, e; z3 E4 Q* U& o" u! h<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>. P3 ~; h0 q: F( ~- \2 u! {  p
<ul>
! ?/ z6 e+ a: T/ [5 P<li>当数据量较大时,仍然具有稳定的查询效率</li>. b6 t1 ~  A5 g% R! l$ y, v% c3 e
</ul>/ j0 V1 K% G3 W1 |: W: n
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
% E1 D( F# ?; d& b: Z<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>* L9 Z7 y6 I' J2 q
<ul>  t# }0 p$ v9 w$ i
<li>与二级缓存配合使用进一步提高查询效率</li>
# F# \. l' i- a& ]/ R</ul>
: n) C' @2 G5 y: a1 C: N6 t<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
6 o; Q" W( i  B  S<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
, M) d( f5 |7 L% D* Z( @+ L& l* k. y1 I* Y: P+ c2 Q
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-14 21:27 , Processed in 0.096985 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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