飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7957

主题

8045

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-11-26 09:47 , Processed in 0.068482 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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