飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8040

主题

8128

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-7 09:29 , Processed in 0.065561 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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