飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8044

主题

8132

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-9 18:56 , Processed in 0.072082 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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