飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8119

主题

8207

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

5 b: K+ m; F7 E! s, s
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

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

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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