飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8040

主题

8128

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-6 21:11 , Processed in 0.068008 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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