飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7952

主题

8040

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26186
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
2 Y9 K2 q+ r1 {/ A
<h3 id="一序言">一、序言</h3>
: \. c% ^+ D: x+ P7 R8 n<h4 id="一背景内容">(一)背景内容</h4>) s& F* _% p3 z% Z& y3 T
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
$ Z; N- K% e' I' @5 e' S<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>5 v: c+ S8 [3 u: W7 l  i( \* x+ @
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>4 S8 K( o; Y4 a, v) T
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
  a( Z+ t3 X; q: l( Y<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
- Z" I3 E  x# W! R( U3 Y" K  \<h4 id="二场景说明">(二)场景说明</h4>/ J' q3 v! [) E# N* {
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>- Y( m* D7 S% z; S( i
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
7 S2 C& Y" `2 J! D' T<h4 id="三前期准备">(三)前期准备</h4>& ?- J* I' c/ |( ~6 v
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
/ N3 p  ^# t( X( a! e1 S0 T9 z<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
& B) ^# p% C' s  H8 d1 A<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>3 L  l/ k  M; H  _1 F" i
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>! M  L! g$ t& i
<h3 id="二一对一查询">二、一对一查询</h3>
+ r) o5 D+ r$ t- Z- d+ ^+ l<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
' o9 ^! m% h  ?+ D( V: C<h4 id="一查询单条记录">(一)查询单条记录</h4>% q6 o' J  q- h. Q  D
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
0 q1 }% b% F- d4 ~<h5 id="1示例代码">1、示例代码</h5>
9 q) t& G! i  s- ~( `$ G3 W1 y<pre><code class="language-java">/**
% A% W$ ^$ d/ y1 J$ L& D * 查询单个学生信息(一个学生对应一个部门)$ Y, A3 c) @: |
*/
, Z+ `+ q) T% y" j, ipublic UserVo getOneUser(Integer userId) {& d' K, W8 s( k7 {! @9 I8 d
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
  s+ v4 c' x! i/ T  j' p        .eq(User::getUserId, userId);# x: h  a! R* S
    // 先查询用户信息3 P+ M4 U2 L, K9 u. l  m
    User user = userMapper.selectOne(wrapper);, [5 v9 @3 F) I! d: K
    // 转化为Vo# K7 Z6 z5 f. y4 s
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
3 V) [! _7 C8 r! @) d/ s    // 从其它表查询信息再封装到Vo6 s3 O( D9 h* G
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);$ A, `9 _) C1 t( z- l, ^" E
    return userVo;; @( H, P& Y/ C1 E6 ?
}& _) g" b+ _$ ?! ?3 {: j3 C
</code></pre>
# V, ~# D; }  W  {" ]<p>附属表信息补充</p>
8 r% W9 S% l- `7 x5 u0 z<pre><code class="language-java">/**
& [( j. H( N, Q * 补充部门名称信息
* A4 q  y8 A6 J, t */9 p! ]0 D, _3 v
private void addDetpNameInfo(UserVo userVo) {
+ W' d) r, E0 ?9 u' x    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)! Q0 {- E1 n* R/ }' E
        .eq(Dept::getDeptId, userVo.getDeptId());
$ H3 M- L3 z  u1 H8 z    Dept dept = deptMapper.selectOne(wrapper);/ A8 `( Q4 ]+ W
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
" a; @+ Y" Y: o0 r}
5 b6 U8 v& {. J( k2 d( r# c" s</code></pre>
. i/ t+ x/ U) p( [<h5 id="2理论分析">2、理论分析</h5>
! \; b/ M" K0 v<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>7 F5 d! ~& c4 ?5 V
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
8 U0 C  Y3 i; o6 S% H8 P<h4 id="二查询多条记录">(二)查询多条记录</h4>' {! U1 Z9 O* W5 r7 F
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>1 e  g0 K( v; k. F7 B$ l; N- |, Q
<h5 id="1示例代码-1">1、示例代码</h5>
6 _6 O9 x0 s; Y8 E<pre><code class="language-java">/**
2 N7 A" G5 e: R) `4 X' V, [ * 批量查询学生信息(一个学生对应一个部门), n# u9 X: s( _
*/
6 v8 l  Y4 K/ o4 T" kpublic List&lt;UserVo&gt; getUserByList() {. B$ r2 [$ Y2 q! f
    // 先查询用户信息(表现形式为列表)" f0 R9 i+ j7 U3 ^% }
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
" N4 s2 K  d* y- L' A+ f    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());* Q# x) q6 e# v+ f
    // 此步骤可以有多个
4 b! m/ R( y* o6 h4 D9 _    addDeptNameInfo(userVos);
0 v3 u4 ~% @, }" v    return userVos;. O) Y$ {8 f' v; u3 e) d0 o6 c
}
; i9 u  k2 C1 l) i4 p</code></pre>
( e1 p2 l# O0 U, K' O$ g, z<p>附属信息补充</p>6 h. H& \  ?( f% ^" _5 y  |
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {
5 n# u- H" B9 T% t$ h2 j" Q    // 提取用户userId,方便批量查询# {" {3 h+ O# L
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());. E7 J' p2 i& G1 D
    // 根据deptId查询deptName(查询前,先做非空判断)
: J3 a6 J; H7 W, {3 |) f+ E5 N9 o    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
4 r' R# ]3 a0 ]' Q& J8 J    // 构造映射关系,方便匹配deptId与deptName* G( O8 R7 q' [0 `: H# t
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
' G! B/ ?# Z4 r; Z, B; Y5 g3 r2 ]    // 封装Vo,并添加到集合中(关键内容)+ ]8 P) E: u2 b6 B% L5 X
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
5 O( W1 J4 O$ Q* L5 T% W}
0 J& Y0 D$ E) B4 ?( X</code></pre>
7 E8 z' B* L3 U$ F, r  Q3 S<h5 id="2理论分析-1">2、理论分析</h5>/ }" a! Q, N( G+ u  E) W& E
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>& C- t8 _- [( A3 \3 b! b9 \; ^
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>& W; ^! P2 z" U9 J
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
+ [' B  R/ X& @* Z3 w9 w1 B<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>1 e0 U7 ]/ r) [7 f
<h5 id="1示例代码-2">1、示例代码</h5>
' c( B, U; R- d% h) |% S/ X1 ?4 r<pre><code class="language-java">/**
% a& @( z; `" |3 K- z  ]( h * 分页查询学生信息(一个学生对应一个部门)
0 w6 G' p  g! w# ~4 a. R */
3 N, `1 ?* g/ h  R. W' b/ lpublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {. f3 M/ X# \  T+ S# E3 \! E$ g/ E
    // 先查询用户信息
0 G5 }* M7 t, ^9 j7 m    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());, b% Q8 I0 b+ k; _# U
    // 初始化Vo- T- k+ O: E# n" b/ e* L. Q
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);" r. `% O& v& }
    if (userVoPage.getRecords().size() &gt; 0) {
/ L6 m( |( ^1 l, |2 {* l        addDeptNameInfo(userVoPage);
3 z  }; F1 ~) r; w! C" I    }
) g/ ~0 g. d7 l7 s1 f    return userVoPage;
+ @" u5 j$ }( X! P- ]+ l1 v, O}: G) C8 l" m+ Y( [* V" i# J
</code></pre>
8 N3 y! V3 _3 z% ]( y* u' `7 s<p>查询补充信息</p>, t) z+ T2 i3 ^) j. v3 T
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
* Z! W! @6 r6 i! P2 x    // 提取用户userId,方便批量查询5 |' V9 f; x' s- k0 b. P
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());- h( c9 c1 g& i- X
    // 根据deptId查询deptName
" @  Z, I2 Q8 l, ]  H+ O* s- N, F    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));. N1 t% \! g: r- @5 T
    // 构造映射关系,方便匹配deptId与deptName
& \& l: Z- `$ U  h1 L9 ?/ N    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
+ _4 W2 ?6 N$ R, J! ?1 h    // 将查询补充的信息添加到Vo中
: O" d% ]" x- S# V$ [/ n0 Y    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
* V6 ^2 n# p- l& i* Q8 H$ D}
2 ?$ S$ m# e8 K% z</code></pre>
1 M8 b5 \' Z- o& R* @3 H<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p># A. t: o* |8 f5 v
<h5 id="2理论分析-2">2、理论分析</h5>$ |8 p- r  l5 W1 e* t2 e' R( {+ t
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
1 E: R2 B! C! E5 M0 |<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
3 E( X# r) D5 u$ L, j$ q<h3 id="三一对多查询">三、一对多查询</h3>8 S* d- T( |! W  }( D
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
  H6 z& p3 k* x6 f& s* t! K<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
: X% ^+ s' G0 z<h5 id="1示例代码-3">1、示例代码</h5>  |0 H6 s) G1 j
<pre><code class="language-java">/**- i% j6 ~" q) L3 n5 Y0 m/ l
* 查询单个部门(其中一个部门有多个用户)
& \, h6 b' R4 l* w# z# g) c( ?4 _0 ?2 z */
: r# c; ~( ?& `3 N. M/ ?8 H% _public DeptVo getOneDept(Integer deptId) {
+ @$ x! A, `5 h  j6 M7 O& ]    // 查询部门基础信息
+ U% d, Q3 n+ f) Z. b. n  S    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);* V- h0 v4 k( t4 Y6 F- i
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);( z3 o) f0 m" G! q3 w
    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
: ~# I# a# u$ l5 e1 f. a% t# T    return deptVo;7 t$ o: o4 P$ m
}
8 x1 V  s! L3 a* ]</code></pre>( k" d9 o, V4 b4 z% L
<p>补充附加信息</p>6 B* q" ~) X8 J9 b! y% D0 b
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {. O( c5 U5 T. }* g4 Y
    // 根据部门deptId查询学生列表$ {* j. R6 H; N2 e& Y, B
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());5 q" F% w; Z2 [. H0 K
    List&lt;User&gt; users = userMapper.selectList(wrapper);% M0 p( q. d& @7 a5 J. l: g3 R
    deptVo.setUsers(users);
% \' l% @& [! }$ u) _+ \; J}
) z# o0 T( |# \1 Q4 R, |, U9 v</code></pre>2 x3 q1 Y8 v- _
<h5 id="2理论分析-3">2、理论分析</h5>
2 B$ Z! h2 D+ K1 \9 l+ z5 x<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>  g+ F& G' h* ~: U
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
5 u) {# x7 q: Y% z( E& x1 l<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
7 M, s6 R7 a( v4 d+ ~) ^1 \<h5 id="1示例代码-4">1、示例代码</h5>* \  d. I( v/ u2 h( c* \
<pre><code class="language-java">/**
2 U9 ]  r) [% x * 查询多个部门(其中一个部门有多个用户)
- K# t4 b- A1 I  u! h8 S$ ^9 o  y */- S$ r/ H. y) b: x9 y/ m0 x
public List&lt;DeptVo&gt; getDeptByList() {
( T" T$ R7 P) m' V    // 按条件查询部门信息
. P* \* Z0 |; T5 Y    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());; g) j/ I# M$ Y1 @! e7 D8 a- s
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
- o6 T4 ]- n8 X* \; D- z/ A% h    if (deptVos.size() &gt; 0) {
2 `+ E: m$ l9 _2 @  O( v  y3 E9 \1 K        addUserInfo(deptVos);- a/ ?: i1 }2 J  t! ^9 p
    }. s- n3 N& t5 {7 q4 d
    return deptVos;7 u/ F) o; D( q3 n  e9 |* ^
}
0 a% q6 e/ {' Z# ?1 B3 G</code></pre>
: b; c. y) T5 A9 b( H<p>补充附加信息</p>6 K" I/ q' ?6 |- O. C  |& Q' U8 Z
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {% I. T# A1 M5 f3 \* }( H
    // 准备deptId方便批量查询用户信息6 n# Z* j0 }' o; E
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());+ h# m( ?4 R2 G) W1 R* a+ T" C
    // 用批量deptId查询用户信息
5 ?( H5 F* p0 e3 C9 I) Y8 s    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));6 ~- |' k$ H7 Q
    // 重点:将用户按照deptId分组, ~: K9 Y" A1 e' Y/ X( F
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
/ l! _( \2 j0 c# ~$ x. ?( v3 R1 o4 V    // 合并结果,构造Vo,添加集合列表
6 d+ D" ^5 J* e    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));& c+ {% [! x' G4 D( ]2 R& e: E
}
4 C0 S1 o$ v; J2 c</code></pre>
% ]" }  m! q/ X2 l' Z- x<h5 id="2理论分析-4">2、理论分析</h5>
5 G, m1 ~! B; z3 e0 ]. S<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>/ d) ^0 W  x* p7 \
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>7 t1 e* _: c" m/ B- Q0 X
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>+ ?' z# c! L6 @1 ~5 P6 n  c
<h5 id="1示例代码-5">1、示例代码</h5>0 m1 e; H) q% c. K& ?6 I7 R1 k8 H( Q
<pre><code class="language-java">/**
: j, P9 A0 j7 Z8 } * 分页查询部门信息(其中一个部门有多个用户)
& u% f0 {9 g+ R* Q3 ^0 y3 L */
; o+ w7 Y  j# }, U; [- kpublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
" K9 k4 V4 Z( ^& B0 V    // 按条件查询部门信息# v  l( ~7 t# p, I6 X! N3 F
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());5 h3 s) A: V1 {; Q
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);# a. s  C8 Y3 B* L
    if (deptVoPage.getRecords().size() &gt; 0) {! v. ]7 }+ Z% s# L6 X, q. w0 M  A
        addUserInfo(deptVoPage);
& B  {# |# o: [1 S+ O" @" ?) `    }
) x4 `" h- a2 o+ e. h5 v    return deptVoPage;. c' ?, _1 T1 l) Y, M
}8 P0 y( V. j8 K( S; J2 J
</code></pre>! M* u! S4 L0 ?
<p>查询补充信息</p>
4 C1 D# l' o$ P5 l<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {7 W) }; i- K/ u2 M+ `
    // 准备deptId方便批量查询用户信息
# }3 x, O9 ], Z$ U. @) r    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());8 w2 F' B& O. ~# ^! p
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);/ {( M! q% Y& u+ M+ A5 k/ H- f
    // 用批量deptId查询用户信息) e% g; n9 w- z; J
    List&lt;User&gt; users = userMapper.selectList(wrapper);+ M& M# X: S5 s# S7 I
    // 重点:将用户按照deptId分组/ v" }* o+ d8 T# y: X' B& G
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
$ t+ _9 {, e2 ]' j$ ~    // 合并结果,构造Vo,添加集合列表" s# W/ ^% r2 R6 q5 m  p! c% s
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));  n# o8 k4 L) d' R
}
: d, \3 r, {0 w+ R: T</code></pre>
; J. A6 ?/ T. z/ |<h5 id="2理论分析-5">2、理论分析</h5>: x% p; I# h3 l
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
; J. M( }$ s1 ^3 x) f% r<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
. Z5 D) W8 r. o0 }" P, z<h3 id="四多对多查询">四、多对多查询</h3>: I$ |* _: D# r$ S
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
$ x6 v& \& k4 u<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
; ^4 Z* Q- o: F% K<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>( A0 e' |) X; }+ C" j+ {' ]& P6 `
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >% k9 k: j1 t3 z$ z) ~/ @
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>5 p6 J6 |# D/ E6 s# U+ @6 o
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
) ^$ {, m3 X, I. x<h5 id="1示例代码-6">1、示例代码</h5>
4 D) V: r$ ^% O+ G  @2 S  x1 ]<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {. M  o+ l6 k9 p+ T# B4 D1 y
    // 通过主键查询学生信息
' ^, g4 Z  m( D: X3 H+ r    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
' m; R2 j4 H- `+ ]    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);, b* T# d+ L& ^
    // 查询匹配关系* _  g9 S: e8 ?7 i$ K7 `
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
# c8 p0 O. L" }: N4 X4 Y- X/ R    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
+ A% f0 E$ m& O4 t! z9 L$ `    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {9 D8 j7 _/ P) C/ U, f$ D
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
! }8 M( ]! U+ q* j2 j        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);' d; a; M" D* Q. {. N1 H
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
! X; Q3 d) E2 F' p5 O        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));& X. |( M" N0 t, `5 u0 ^
        studentVo.setSubList(subBoList);; b1 R3 W9 s* A- d" {% Q
    }
: ?6 b0 L2 g- f    return studentVo;4 @) j" x- N4 x7 i4 I& Y/ D" @
}0 L( A. I4 X* l
</code></pre># x$ w5 ^8 Y/ L4 g6 a' X9 ~
<h5 id="2理论分析-6">2、理论分析</h5>0 E! m( x% S4 _
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>+ l; F/ [+ W0 B: }/ Y$ k/ e8 w
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
' ^! t4 y" r/ w+ a+ F. L<h5 id="1示例代码-7">1、示例代码</h5>0 u+ J% D2 q" J- D( d. G
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
/ ]* u6 y; h$ K. z0 I    // 通过主键查询学生信息# l9 B, ^4 N$ w1 y- {( }
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
+ _7 g4 Y8 ?! \# W    // 批量查询学生ID5 `" w) o) U! q
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
* M2 t; j; J% ?    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
! t7 g8 u2 j: u  q3 H1 Q& A  k* S& M    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);) G1 B/ _- x9 \  }" T; Y. h/ _3 [
    // 批量查询课程ID# e8 y$ \! V+ f* D- q3 q6 d
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());0 c3 Y) B, Y" o3 C5 p
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {! [0 V; i( \: x. l  B! y2 w
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
* C5 {6 s8 ^7 F5 s# [1 p, T) U        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
- o( J9 _  J2 e2 y        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);" {  g" p4 G+ j; N1 i
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
7 `* x9 L# s2 O+ Q( M# k* j8 e        for (StudentVo studentVo : studentVoList) {& j: y# Y6 L5 w/ i7 ]2 w
            // 获取课程列表
, G6 D, Y8 i" I& V) B            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
2 g) H0 n: u  W; i$ K' C, x            // 填充分数
* B: u4 z9 X9 H$ k6 P            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));9 ?- E* A& j( i& j! p2 P, M
            studentVo.setSubList(list);
: O6 Q, c4 h5 {        }
; M, T. t* W7 J0 |/ d* m# l1 N    }7 z7 ]& F' O4 Z- \) y0 N
    return studentVoList;3 H, w/ \2 D; [# F3 @! K" W6 [% U
}" _  f. l8 S, m4 h6 `* s
</code></pre>' f  }: ~* Q0 m6 u5 A  }& @
<h5 id="2理论分析-7">2、理论分析</h5>
9 L- _& z: L' a7 ~' J<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>% M2 c8 {* o2 J! L
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4># P; s3 Y$ J' Y8 g0 }
<h5 id="1示例代码-8">1、示例代码</h5>
/ a! x- A0 g, P1 ^5 o' j<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
9 G- B! U+ ~& ^: a    // 通过主键查询学生信息1 [8 S* }& [: T# T, e
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);; P2 @# |) ]1 R' ]# p4 @
    // 批量查询学生ID
4 N/ A& Y; l" h    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
# L6 Y' y# J# C% b    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);+ H! {- v* k# S4 G7 T
    // 通过学生ID查询课程分数
5 \3 ], n9 E3 i' k- J    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);4 v4 A: a5 @, q6 u+ _. \
    // 批量查询课程ID
7 s1 }  R2 u  ^+ c/ e. d    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());% ?8 B& o& f# d8 }2 @$ R8 e# v5 ~
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {; Z3 h2 P5 p2 f
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);" V  V# ]& I  z8 g; b$ {
        // 学生ID查询课程ID组7 d; c4 `. K$ w" L4 E8 H$ A
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));. S4 ^+ J" o! y! W! p

% z) e2 [1 ^& f: A9 l        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
. l8 Z0 Z/ K9 Q4 ]* p        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
* ?6 k1 l0 W, Z- `        for (StudentVo studentVo : studentVoPage.getRecords()) {
' g9 h2 U, d  ]& {! `. U" {. a            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));, {6 }0 H# ]# q2 E) o
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
4 g% V8 r2 \% O; [4 g" D            studentVo.setSubList(list);
4 _8 t8 |6 m3 ~5 ~        }
* f9 z: t+ y7 z* `5 l    }4 G/ i& z& Q: K, r  q: \; N
    return studentVoPage;( `& Z- T+ x& |+ d$ t
}
: T5 t) L/ i4 a: c</code></pre>
  n1 B' Q& D  o' Z3 E<h5 id="2理论分析-8">2、理论分析</h5>
6 E( ?2 O! {0 k" u) A2 q<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
& |# ?: V* s0 I4 |! ~0 [) O<h3 id="五总结与拓展">五、总结与拓展</h3>, A4 O& c+ J+ k0 I
<h4 id="一总结">(一)总结</h4>
6 q5 q& u# k  o+ b<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
6 N3 \* u% Z$ j<ul>
5 W. R. j) D' h( l' k1 X  X. E. W<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
4 _2 `7 R! ]- @" @% S( g<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>4 k3 o" S9 c: Z' H$ J
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>/ T6 V. @( W5 a+ u+ J
</ul>
0 `9 M- J: W9 v3 p& j5 l4 W! D<h4 id="二拓展">(二)拓展</h4>
0 ~7 ~" ^6 o8 f! H- D% M' c7 t0 r<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
$ Z; E, o3 _4 @<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>0 y. J$ [; @9 z; Q. w5 Q# C
<ul>
" G! S( J0 v5 G, z# w  }% \: [<li>当数据量较大时,仍然具有稳定的查询效率</li>
) t9 t+ D0 r6 t" Q: f) Z</ul>2 P! g9 e4 {) X$ u2 Y6 l
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
/ J) k" s# I5 A<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
. h' R/ {. S* _. O2 Q7 ~<ul>
! L% o- ~5 k2 r2 ]<li>与二级缓存配合使用进一步提高查询效率</li>( J& x. ?8 a& p+ o- m; F  w
</ul>/ n3 c2 Q9 T# R0 M
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
( _9 a) K) e5 a! n  h$ u4 ^# ~<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>) {& z' ]' @# T: Q8 c

' Q: m. Z" ~' o" p
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-11-23 22:51 , Processed in 0.070726 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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