飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8042

主题

8130

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-9 06:02 , Processed in 0.176081 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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