飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8042

主题

8130

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26456
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
8 F6 O% Y6 m6 u9 P
<h3 id="一序言">一、序言</h3>
. t( L8 ?! a$ Y  ]: p$ b<h4 id="一背景内容">(一)背景内容</h4>
: O8 `9 x) {& \: X) X* A, [<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
7 J0 q+ `' ^5 Q- f: ]/ Q/ j<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
% X. ?2 _( E2 u( @  @: L; u& d<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>& o2 J3 X2 a6 p' a. N7 t; Z
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
( J3 ]4 P9 V. b7 ?! _7 M<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
0 Z0 j2 d- b# o8 h<h4 id="二场景说明">(二)场景说明</h4>
% L% Q9 m* Y2 S, S- y<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p># B/ n5 `) T1 k' S  d6 c) J1 S
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
- I4 ?2 K! k0 G<h4 id="三前期准备">(三)前期准备</h4>8 S6 ^0 y/ j3 p! ~8 p
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
* {( G7 f/ e' m0 }: M<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >8 e& B- V& t. y+ U6 A- b1 x2 b/ A. W  I
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>% E; t1 S0 y7 m2 P3 Q) g- _( K4 N
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>0 {  O3 _8 x7 ~0 ]; ^4 U4 {
<h3 id="二一对一查询">二、一对一查询</h3>% q; N6 Q1 I) |2 V: `- A$ O
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>* c6 ?# l$ D* Z% r6 F
<h4 id="一查询单条记录">(一)查询单条记录</h4>+ D* u* K9 v) M  l2 h- E; z
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>5 R2 Q. p, y2 \, Z
<h5 id="1示例代码">1、示例代码</h5>. A/ i/ J4 X: \% h
<pre><code class="language-java">/**
5 g, B8 C# W6 } * 查询单个学生信息(一个学生对应一个部门)
/ G$ U9 w& c2 }& P */" l- [5 }, Y. y+ S/ L6 a
public UserVo getOneUser(Integer userId) {
& b$ J/ a( H( V6 j+ {, n; i# d    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)7 H0 ~/ ~+ K* q8 ?) i: Q; ^
        .eq(User::getUserId, userId);
- d8 j( K6 u$ s) x8 l! K    // 先查询用户信息; o% c: c/ @- o# L' p. S8 t/ C
    User user = userMapper.selectOne(wrapper);- M. L8 |9 n$ p) w9 m' f
    // 转化为Vo0 p' O; {/ [8 Z- N# Y$ W$ n" R
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);" f3 h- Z- @/ y( x1 _
    // 从其它表查询信息再封装到Vo
& B9 F1 c1 c  a# e3 e7 @7 {2 b7 k    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
; y0 E* e- i7 y5 M% |" h  D- C    return userVo;
7 a6 k, H& ?8 Y9 c* `; s}
1 ^  n5 Z/ p1 |. G1 r# J5 p</code></pre>
( ^5 T2 T6 |' z  v! x- m<p>附属表信息补充</p>: u, S% M6 H! G/ G
<pre><code class="language-java">/**7 c0 k9 c. l3 j: d$ u3 V- Z4 O
* 补充部门名称信息
9 u. p. K2 y# j! M  p */- W8 e2 |* Q/ F, U' t( F
private void addDetpNameInfo(UserVo userVo) {0 t; }5 F1 a& A# D. T( N
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
# k5 f8 o4 t. T        .eq(Dept::getDeptId, userVo.getDeptId());( @1 @, f& s( U
    Dept dept = deptMapper.selectOne(wrapper);
# [0 t- D- @' O+ p. _) l2 F    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
  {8 G/ ?" @# F7 ^}) ~+ ^/ V- s4 I4 r9 w, t. C$ J6 H
</code></pre>
! \( s1 e) Q% C  ^  Y  Y& h<h5 id="2理论分析">2、理论分析</h5>' p( }4 P; n/ {
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>2 @4 H. a; Y' m  o1 h
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
8 o( G2 N: Q0 ~' z& |<h4 id="二查询多条记录">(二)查询多条记录</h4>7 _  o3 ], |) _' h/ p0 w
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>6 k- a, B) g/ R# w7 \
<h5 id="1示例代码-1">1、示例代码</h5>
; |% _4 @+ k0 `<pre><code class="language-java">/**
( D+ ]8 b2 b8 ^. H& T# _7 q3 m * 批量查询学生信息(一个学生对应一个部门)9 U2 ?2 W* g( [! n
*/6 T$ m  a. F! \6 o# Y9 \5 Z* Y  L
public List&lt;UserVo&gt; getUserByList() {
$ ?5 w8 b4 t8 |% s4 p* j8 Z    // 先查询用户信息(表现形式为列表)
$ O, y0 w) R) Y$ E    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());  a- t- I) u  x. B) o; j/ V
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
2 g6 [0 L2 t! M, o0 ~    // 此步骤可以有多个
  [& v2 ]- t1 {* T7 v' |, H    addDeptNameInfo(userVos);8 @6 U. `3 J8 i# b* M
    return userVos;4 I4 w. B$ l- u
}
% S! H" e9 ~5 L: {" m</code></pre>2 @+ H" n, _% i( Q
<p>附属信息补充</p>
2 n5 X; m8 |, {7 G+ o<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {
" E- m# v! z! w7 \    // 提取用户userId,方便批量查询- T, p! g5 O5 e- m/ I
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
: @" V% w0 l* d6 A; m7 H    // 根据deptId查询deptName(查询前,先做非空判断)
* }; ]. m1 O( I* e6 G2 x    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));9 ~- s; f. _3 E$ H
    // 构造映射关系,方便匹配deptId与deptName
) `& _& q' E% R6 ~: X# E    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));" {8 N+ b2 f/ U# q8 Y! g. }3 A
    // 封装Vo,并添加到集合中(关键内容)
5 d; A# [! F% Q3 e; V% _    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));: N. |) @1 a, Y1 g7 C* m! `
}
. I/ C* r9 c( e7 _! O9 k) Q  e  b</code></pre>* n6 O- M0 m5 |5 [  S* a9 [% p
<h5 id="2理论分析-1">2、理论分析</h5>, t1 R! G/ b+ i, B4 X
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
, y7 J( @' q( Z2 `) \<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
% J% n" U- l+ u( i6 X' F<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>6 ~3 i* u4 v7 T5 r5 |. h
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
; W/ T# o7 w1 B% E! o, Z<h5 id="1示例代码-2">1、示例代码</h5>4 ?! C! Q- h4 K; V
<pre><code class="language-java">/**. O2 G0 W) q1 Y! a% K/ H- T; w9 K/ E
* 分页查询学生信息(一个学生对应一个部门)4 t5 Q2 p3 u7 D3 r$ \( n
*/" w9 v1 l* V: \# x! v
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {! o- M9 S$ l! o
    // 先查询用户信息" v' r/ B$ s! W1 h" I
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());( e% k" {7 r7 V! B3 j" e
    // 初始化Vo7 k7 H" r1 R$ S' ]' i
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
4 r# n' G( O2 e  W* K    if (userVoPage.getRecords().size() &gt; 0) {
. {  U4 M" b  p+ E) [# A8 H        addDeptNameInfo(userVoPage);6 O- V  b  Q+ q1 W3 U. b/ e
    }
- D3 x. g- M' c+ h/ s    return userVoPage;" c" U& o$ j  x  a0 m3 k. Y
}; ~& B  c" d: ]# ~  ^7 c
</code></pre>
: s  x  I) i* V! i# S<p>查询补充信息</p>5 \& O* t+ ^& O9 ]# a8 l# _5 I$ N
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
! W' x! B! Y( v( ?7 P    // 提取用户userId,方便批量查询+ u+ x. g. ]) {2 k
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());0 Q3 f9 l) C: F: ~: g4 U, W
    // 根据deptId查询deptName2 i( d, q6 q# _4 E7 {
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
$ Z9 T/ Q' S" T+ H, v8 i4 w    // 构造映射关系,方便匹配deptId与deptName
: a5 T6 C& d; W7 Z/ l- ]    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
8 k6 d/ O) T, y/ I    // 将查询补充的信息添加到Vo中; x2 Q6 w% o9 \3 m+ Z3 h' P. s
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));  E0 E) {# {4 Q9 D
}$ M! i. A- v# d' M/ V
</code></pre>& X2 U4 w0 ?6 @; f! k: @- @
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>5 V; A, x' z! r: V( R
<h5 id="2理论分析-2">2、理论分析</h5>' T1 j2 r# \3 u* \& W4 y4 P! H
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>, c. i. |5 j  q
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>) z1 F) m8 r: d; T& Q- b
<h3 id="三一对多查询">三、一对多查询</h3>
7 X0 |  m0 V4 i<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p># @  H" W2 n4 T! F2 Z- |+ N% K
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
7 w/ h& ?- }/ e& B<h5 id="1示例代码-3">1、示例代码</h5>, H6 a6 M; v" ^
<pre><code class="language-java">/**& e' G) ~; Y( E' p! T0 c  C
* 查询单个部门(其中一个部门有多个用户)- J4 K; j& d8 i% N" J1 ^& f% H
*/+ U: Y# S: O4 V7 E3 y! y
public DeptVo getOneDept(Integer deptId) {
! o, t, K- c0 l- ]; _) e. B' D    // 查询部门基础信息; j& N% q& K) |8 O/ b8 t
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
4 }* O$ L! Z5 o3 ^2 c2 m2 i    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);5 t6 A+ ]% }; z& v$ v, S
    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);4 W  P+ c) e0 r6 {1 T$ y
    return deptVo;
9 k0 U/ [2 `/ X}; z( X5 M& A" N. `8 d/ F
</code></pre>8 h# D+ d1 k# h6 H
<p>补充附加信息</p>! s5 b! w# m3 G
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
4 J1 P' D2 `: P& A! h# N7 Q7 b    // 根据部门deptId查询学生列表% [2 [; l! Z( G7 `
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
+ m, f" z1 n( F! j6 ~  J2 Q    List&lt;User&gt; users = userMapper.selectList(wrapper);; x! A$ ^, t8 l2 s) c+ R, [) P
    deptVo.setUsers(users);
4 o, w5 R+ O% @1 ]/ R3 h}, C$ Y8 _+ I% ]  D7 a0 N
</code></pre>
- \* b+ l! b. C! A3 z<h5 id="2理论分析-3">2、理论分析</h5>
2 F; Y) H7 S- h$ O- N: ^1 @3 x<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>, Z' h$ `, ~- E, |  r1 E
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>' p) Z& S, c( Q- Y! N& ?1 e0 {
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
  t. x# }4 u7 G( o1 v" U<h5 id="1示例代码-4">1、示例代码</h5>) t* w+ h1 d) F1 Q
<pre><code class="language-java">/**4 C8 w% V6 b% C# p
* 查询多个部门(其中一个部门有多个用户)2 k4 K' o9 @# K
*/  M' H0 W8 r& v+ \* c
public List&lt;DeptVo&gt; getDeptByList() {  J5 U' o# ~! N# T9 c  P
    // 按条件查询部门信息
( Q1 Z5 l+ t9 N* u; r    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
8 ^- g6 ?6 @0 S( V# G- x, W. ?    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());. @! S) k: b( l. J7 X, R
    if (deptVos.size() &gt; 0) {/ A* S$ A2 i( k5 w: s
        addUserInfo(deptVos);
( A  h2 P  w1 u' j6 S% w    }
4 m; h$ U8 o  Y$ m    return deptVos;- |; U/ G$ |) g# T% I! s
}
" Q& b' h: B2 T% S</code></pre>
+ Y9 ]9 q6 M$ b3 f( w- c<p>补充附加信息</p>
' p+ s1 f" X2 }+ j/ `/ K, W/ l1 q<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
' }1 j# r! U: |: E7 R5 @    // 准备deptId方便批量查询用户信息8 b. R% n1 T0 F* j" ?" N! J6 q9 K
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
6 ]' O/ R: V/ l2 ~    // 用批量deptId查询用户信息6 X8 \3 ]" {  b
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
0 e" O, o  h  [# Y. f& y% c    // 重点:将用户按照deptId分组
& E& @# R; N1 V4 u    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));4 }/ O5 }# V$ v- Z
    // 合并结果,构造Vo,添加集合列表6 s& {& o. v2 {
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));7 w$ S- Y- @* b! j* E& g
}
; {7 e; E6 b+ X+ B; j</code></pre>9 I. u1 R! t/ Z0 J( R
<h5 id="2理论分析-4">2、理论分析</h5>8 n% j) A& c! X( ^
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>* B0 G3 s$ v. g* }2 i7 e
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
+ @$ b# v+ C9 U<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
, d7 T1 d# K/ h) Z1 U: S! e0 F. K! N<h5 id="1示例代码-5">1、示例代码</h5>
0 ?  ^) h/ b; p/ P5 D. Z/ p' X<pre><code class="language-java">/**$ A$ v& p* M) }/ j5 F+ W& b
* 分页查询部门信息(其中一个部门有多个用户)7 n0 [& ~4 K* ~% A6 p  Z8 @9 o5 j
*/' `" g, ?. X, e# a
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
: |% Q4 P0 C9 c) ]- K2 Y  }4 ]! N    // 按条件查询部门信息2 T1 {$ G3 _3 a. f, P
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());5 G1 Y! s& j. ?- t
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
1 s! l* U: w2 [7 o    if (deptVoPage.getRecords().size() &gt; 0) {
: f9 E$ X6 O9 V2 {; e        addUserInfo(deptVoPage);
; }8 F& D/ _! N$ i0 R3 v/ u0 x7 C& u, I    }
' M5 i8 _+ I! H# E& w" v; t    return deptVoPage;
( b: c- |, G, Q. F& ?}6 H4 G# {2 Q7 f4 o  ~
</code></pre>
' @# c* J% Z4 }5 k4 c8 ~, }, R) e<p>查询补充信息</p>
. f+ {& i+ B: {<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
) M0 s; O% X  Q3 c3 A0 `& A    // 准备deptId方便批量查询用户信息8 G6 b$ @! e( n8 z4 v* }) n
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
$ B! I) x+ a7 [. O- ?. U& \    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);) Y& H6 K% J: O( G- P
    // 用批量deptId查询用户信息
0 N) w) R( b& }& @    List&lt;User&gt; users = userMapper.selectList(wrapper);" f/ q( D8 B# h# d: Z
    // 重点:将用户按照deptId分组+ m1 D  D' A! ?/ u) \
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
# j3 M- Z2 Q4 G, @: ~( n4 {    // 合并结果,构造Vo,添加集合列表
! z! `2 y9 @" W& r8 S1 `0 k    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
# m5 V, E! }* I$ ]* L& Y2 m}3 m/ k5 E6 ^5 h) g. t2 ?
</code></pre>
  |. S$ S$ u4 Z3 e- J7 |<h5 id="2理论分析-5">2、理论分析</h5>
9 R: ^8 _$ D6 ~8 }# y; n<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
; o2 S/ ~9 u+ s<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
9 m/ {! `7 \6 O& R2 c<h3 id="四多对多查询">四、多对多查询</h3>
( p' M% h- _% v" {* U<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>& h7 F/ F" t9 r2 O2 R% w7 Q
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>% v+ w! X; g; [( a
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>! F, H. J8 D+ \% Z6 _5 c
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
. x! w3 d  c! |" n<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
' P0 `/ P$ x# E. v0 m9 d0 l/ z! g7 \<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>& I) ~" q3 E- R3 L7 n) i3 p; K
<h5 id="1示例代码-6">1、示例代码</h5>
6 U. K5 E0 V1 j<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {) V( X# x$ u4 x. G; S7 F9 |
    // 通过主键查询学生信息
5 e! R! \! |: y! W# A    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);+ D! @* }1 p5 e0 }
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
: g& A7 _, w7 v    // 查询匹配关系8 n+ T9 ^& [7 u. r8 w4 c) P
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
9 A, }  i8 ?6 U    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
5 z4 a9 S( e; |5 m0 h    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {$ E% r$ G( S# m/ Z7 K! g1 l! k
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));' P3 i+ R- A9 \9 h7 Y
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
* p  C1 u* I6 G$ T; |        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);5 t5 U, {- k: u0 }* L
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
% f4 s& ]9 ?% N, h# V# i/ |        studentVo.setSubList(subBoList);
- g7 o0 c. L, S& ]4 U    }7 H) u; l* V( A' `
    return studentVo;! t1 B7 P% x7 V- h$ c6 }/ Z" U
}
0 C6 q. t* }6 t+ _& f5 z0 k# \; K</code></pre>
8 m! k1 [- n, n6 j9 c<h5 id="2理论分析-6">2、理论分析</h5>/ ]% V+ q- y9 P" v5 [9 |! E# I9 ]
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>+ D' c: |  ]! p
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
' e/ k, G8 U9 U) j) L( l5 _<h5 id="1示例代码-7">1、示例代码</h5>* n8 c$ `4 V+ O. a1 z8 o" e
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
# @: |1 I6 C# p. a    // 通过主键查询学生信息
) [+ x$ V. d, @    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);8 z* W. e) L' \: B
    // 批量查询学生ID5 p; w' h  O' W' n0 L
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());! f! s' }9 G) T  T
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);* N. `, i. K0 C# P
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);7 b4 M1 q) u% \# |8 ?
    // 批量查询课程ID* n  z. `) M! Q2 O* d4 ?
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
' c1 x/ L( Y4 T- I8 |0 J  F    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {3 h) Q& D4 A2 W6 z* F0 N
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);, z+ s% R! f0 h( X5 s! D. p/ _
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
* P  H( t7 o9 r. o0 C        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
! `" H0 y+ m4 \6 t5 [1 T& s, K! q# v        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));; q! K" t& Y, x0 {. L7 q5 c8 j
        for (StudentVo studentVo : studentVoList) {
# m- T- Y& y; ?1 @) S            // 获取课程列表" p, ~0 o/ U9 i: d
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
$ ?( b6 l# z9 w8 _4 t# M) p5 m            // 填充分数6 ?0 k) l1 {( _$ c: R
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));% b3 P3 o2 I! F7 q
            studentVo.setSubList(list);
) [4 [  J0 P0 j4 M! ?8 W6 I; m        }
. B+ f4 ]3 b5 W9 i. j$ d- ], A    }% n7 L8 r2 F& f9 l) o+ O( c
    return studentVoList;
2 E& T, m9 o2 s8 g! w  s. P" W& _}
) A. k( t* y+ f</code></pre>; f( S# E: k  r% ^1 G# j& O
<h5 id="2理论分析-7">2、理论分析</h5>
; C8 s3 H- m5 L( m: R- \<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>7 F" r. r: [3 ~" |- L
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
* j. Y. e2 n( M<h5 id="1示例代码-8">1、示例代码</h5>
  a: L- ^& @/ o, S- l( l! z: z<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
& g/ \! q" @7 j( d) B6 U    // 通过主键查询学生信息( _9 ?9 z. M6 h- |2 M
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
; O0 r' j( T2 n8 e! h2 ~6 f8 s5 U    // 批量查询学生ID
: \4 x- f( c( l    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());% n+ _! r5 p- w$ v# }. ?( o
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
* N% s2 E$ b/ H" z( b, A9 h    // 通过学生ID查询课程分数2 v) q4 t0 f1 [' c$ {* A
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
  j$ E* O' {$ I3 V; C    // 批量查询课程ID/ u' r9 `7 Q( E) U. |* \
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());1 m9 [* [9 I5 d5 x
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
- X/ J6 |' b; R! H3 D! V1 {        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);! }. m8 }; s% z; q
        // 学生ID查询课程ID组, B5 j7 f+ _4 X
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));* x# T/ W( I+ t% ]0 L5 t. a$ Y
5 r' E$ E9 q$ j' X- M8 {7 R- A  h
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));% i' o# F1 `1 `- `1 [* e
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
/ [+ h% [$ i+ y; E1 ^2 `' c- E% k8 g        for (StudentVo studentVo : studentVoPage.getRecords()) {' a" f9 ~& [0 Q2 _2 H
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));% I) S1 _) d' Q: n5 ~
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));* l, Y9 ~0 A+ S& |* J2 @
            studentVo.setSubList(list);
6 }5 o3 H( |! Y( S) k        }
/ z# j# u( P/ Y    }
& m9 C3 ^" I) B# [, w# t    return studentVoPage;
& d; S% N5 X' L" b}
1 i9 V! {% Z9 o* a* i</code></pre>
) d' t+ r& W7 ~% _. W<h5 id="2理论分析-8">2、理论分析</h5>
% X2 i9 |4 f# t) {1 {: Q& y<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>* I/ b3 g) S. `" ]4 m: r
<h3 id="五总结与拓展">五、总结与拓展</h3>
; p" f2 [' q* i3 ]8 B+ h2 ~<h4 id="一总结">(一)总结</h4>
# O7 W: g& l# w7 t( H1 L<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>/ a0 b6 H6 @+ G- K  ^) e5 T1 ]
<ul>6 P) K# f$ A0 z6 }1 C
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
: j# A! R& L* I# G<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>0 Y* l; {4 `! H0 s9 U9 W, `
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
: t! d5 r) a' e3 b' ~2 b0 g) y- [</ul>
1 v6 p1 J) b; N0 K, E4 {1 p<h4 id="二拓展">(二)拓展</h4>
; ]/ x* r% e+ v" s$ r- m& s<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
/ w2 V. Y% m6 r2 r+ v<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>8 [0 ~9 v3 b* F; N. a
<ul># ^& Z* C2 h6 y# e* i
<li>当数据量较大时,仍然具有稳定的查询效率</li>; L& \' K" [" `8 V) T/ w! k
</ul>
, w6 K; e% b, t2 T<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
+ g0 Y5 j: J: F( N4 M( {% ]) K<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>, t" P5 A/ ]6 A9 _3 b; n1 P
<ul>& G2 X; |; B9 g' O
<li>与二级缓存配合使用进一步提高查询效率</li>
& |- ~/ I+ T. l2 u% [. B</ul>( r4 W% k6 b- m6 K" x! c
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>6 Q$ ^. }9 {/ U% G# S1 d+ u. p
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
9 p0 e3 S8 H5 n5 K* d* b% P0 O/ x3 u) o0 @6 ~6 U7 m
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-8 23:02 , Processed in 0.133741 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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