飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8042

主题

8130

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26456
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
- f! x! N: K9 n( U" D. P" D
<h3 id="一序言">一、序言</h3>
( ?4 C8 N: I1 c<h4 id="一背景内容">(一)背景内容</h4>  ^! Q5 b# ?/ p% X+ n
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>7 c8 P# k; H, p2 F% n! Q* y$ X
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
: x% p: P: l6 f4 g) t<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>6 z# @. h$ n4 _5 o  {7 z& \
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
# b+ _6 O* O$ Q8 W# Z<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
- O( ^# m1 H) M( p<h4 id="二场景说明">(二)场景说明</h4>; C6 \( R* |/ |
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>. Y5 _; F6 e- b. c( S
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
1 i/ R" L/ Y  K<h4 id="三前期准备">(三)前期准备</h4>; I' B8 ]$ w7 k2 V% d
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>! `. ]( J7 I9 L0 x- w0 r8 \
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
. {2 c" ]: I1 W8 T  O# w0 `/ W<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
2 m* \5 |% k9 s<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
2 c" [# q! B* ]<h3 id="二一对一查询">二、一对一查询</h3>% D! z/ t& j: N$ L1 K" c! Q$ B/ [
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>$ {/ d. u& e9 h4 n+ O4 p! |
<h4 id="一查询单条记录">(一)查询单条记录</h4># c: a8 K& l! V( t- M1 W
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>) O3 @# M6 m! I  |9 m
<h5 id="1示例代码">1、示例代码</h5>) I3 @, o* L% ]0 w* _
<pre><code class="language-java">/**
5 m- }( t2 v% _3 v. B) H * 查询单个学生信息(一个学生对应一个部门)0 i/ J$ |5 |2 o, J6 p$ X
*/: R" F- `  Z2 @0 {/ B1 ?
public UserVo getOneUser(Integer userId) {9 y, D7 s* O6 N0 b6 l
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
" U& J+ u0 Y7 I4 @0 N. M7 I        .eq(User::getUserId, userId);9 Z! ]1 Z2 Y$ R' e' b6 l. u
    // 先查询用户信息, J/ C( O% {' Q6 f
    User user = userMapper.selectOne(wrapper);+ w- t  r# E7 P
    // 转化为Vo
% \2 S- q' r4 c5 {# R6 f9 I    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
1 _; U. q0 q, u# M    // 从其它表查询信息再封装到Vo# P6 \2 c  G& F- D% B- H
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
0 [4 b1 Y3 h% L6 s# v  m+ [    return userVo;- L7 P% r; g: B- V$ q9 F# l
}; \5 `# U5 k- M) P
</code></pre>7 V- |) v3 x7 h
<p>附属表信息补充</p>7 N: {2 L( T3 B- E
<pre><code class="language-java">/**
) R0 j; r, X3 Q1 q * 补充部门名称信息' q0 E$ l: R3 t" Y0 y
*/: h5 ^, u$ }  F$ W4 d: j
private void addDetpNameInfo(UserVo userVo) {' n0 L7 F5 M2 m3 e
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
( F" ~# k/ p& D3 f        .eq(Dept::getDeptId, userVo.getDeptId());
# O5 @* ]) p, |; W    Dept dept = deptMapper.selectOne(wrapper);
5 V2 D1 G* ~, G    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
& f' D! e# ^+ Q' o7 ^3 a: j9 m}' G( w8 v# w" p8 ]9 o
</code></pre>
$ o) |  H, P- ^8 {. d, N, k- O5 n5 }<h5 id="2理论分析">2、理论分析</h5>8 \1 d" ^0 s- n" S0 _0 S- ]3 k& m
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>; D8 L& y6 W2 p7 _1 O5 U" O3 y
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
! B. @$ }' m- E" O  E: E$ \& t<h4 id="二查询多条记录">(二)查询多条记录</h4>4 \. J2 j- P( c# Y, Z3 ~' K' |4 C
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
! N) W  _$ F" ^6 r7 I4 z' f<h5 id="1示例代码-1">1、示例代码</h5>* e+ o7 j" H; U# X
<pre><code class="language-java">/**
1 R- K/ E* Q# `: [4 p * 批量查询学生信息(一个学生对应一个部门)
: P; X- s' S0 ? */( p1 X( n: m5 W* {# a0 h3 T
public List&lt;UserVo&gt; getUserByList() {7 e1 y6 A$ `4 W% N+ v  j2 e
    // 先查询用户信息(表现形式为列表)0 }3 K' i- U+ q: `+ ?! ~
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
; @1 m: V! t* q4 ~! R    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
7 Q5 c( n7 J/ k' F/ n/ H    // 此步骤可以有多个. n1 C% J" [, l! o6 ~
    addDeptNameInfo(userVos);
5 U! B3 z& |& `, U    return userVos;: G7 p) \0 n6 E  x! g
}0 q' G& t6 V$ M% d' b4 ^
</code></pre>: _8 c1 {* H  T+ [7 ^
<p>附属信息补充</p>
- x  ~9 E% A. M2 s" {# t<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {
" L: O6 j# O* y' s; q- m1 y8 l    // 提取用户userId,方便批量查询
- h9 T' |! o) J    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
$ f6 @3 E* q. P7 V! K: C    // 根据deptId查询deptName(查询前,先做非空判断)( p% e, g2 f) B0 y% j! @4 H. w
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
, U% [' V3 `' Y7 J5 q1 g    // 构造映射关系,方便匹配deptId与deptName4 y' C* y, [0 |+ T- P. C2 A
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
8 v5 \2 X. S9 J( `/ |9 C    // 封装Vo,并添加到集合中(关键内容)
0 W- M& ?) M+ ]    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
5 s, B3 R: j1 ?, r2 E& h. [" C}& S! g2 ]7 e9 h, n/ I
</code></pre>
2 o0 X# D! U& n<h5 id="2理论分析-1">2、理论分析</h5>: v3 n: S6 u$ h, m! Y4 Q
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>$ s! I+ H6 n! V8 X+ k
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>  V' L& K& l) p6 x" j/ b
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>9 j3 z5 L) y5 _
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
+ K) g* |# P: Z' [2 r/ Q' m<h5 id="1示例代码-2">1、示例代码</h5>
5 q* X6 |0 k9 `5 H! s& |<pre><code class="language-java">/**6 a7 `: {9 K0 N3 j  a' B
* 分页查询学生信息(一个学生对应一个部门)7 Q8 G( s; M/ [* V
*/2 J! b" j/ S$ U, X3 U
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {; P- n- l4 V! `: T/ n
    // 先查询用户信息
# I  F, o9 ~, `$ q% v    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
7 M/ s, T! e: g) g    // 初始化Vo: Y: q) F  ?6 y/ J3 O% m8 h$ y+ F
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);" L: u$ _1 P! n" Z- w" y5 ^
    if (userVoPage.getRecords().size() &gt; 0) {0 U, l  f& O7 B) J
        addDeptNameInfo(userVoPage);. b3 g: n" m1 c) N; h. N' D
    }5 G* \! o- n, \7 D
    return userVoPage;
/ j* f% H% A% W6 G7 Q0 i}
7 h( N$ [" v% I9 J* K1 @$ W& M</code></pre>4 ~5 y1 u0 n" V6 H4 K
<p>查询补充信息</p>
+ @0 |( t1 H/ j( z6 Z<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {0 i6 h9 V7 x: q: l- P% W$ W
    // 提取用户userId,方便批量查询
) t/ [. P, ^: A9 u( T" ~9 j: Z    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());# u6 v: U7 }- R2 Y$ i
    // 根据deptId查询deptName  P* {- g! C2 j7 H7 j' V
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));; @4 G) g% t, \! l/ X& m' f4 p
    // 构造映射关系,方便匹配deptId与deptName
4 V8 K) o9 [3 O+ s    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
+ b* `1 s! B" c! F9 q    // 将查询补充的信息添加到Vo中
& ?  H  X/ p8 [4 t- c    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));1 C" T8 _+ b% h  N% f
}
% l5 E% j' P8 Z+ o</code></pre>
3 `1 I" N8 F. I& g6 ~! C! O<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
) E% Y$ Z8 ]8 a  q" a' |# V4 ^<h5 id="2理论分析-2">2、理论分析</h5>& s! S! a8 {% F' k/ u
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>' E5 {- J0 L. Q3 @: n6 s0 I
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>- I, f. d1 K% O% B; ]
<h3 id="三一对多查询">三、一对多查询</h3>
% y# r+ p3 o7 n# p. Q/ R<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>0 S* v* ]* `7 `7 e2 E
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>3 z/ x1 b. h. l; K  T
<h5 id="1示例代码-3">1、示例代码</h5>
( @; c& F" o& M7 {8 B- p<pre><code class="language-java">/**
; P# m7 i7 ~; J3 p: B * 查询单个部门(其中一个部门有多个用户)
. Z! x9 {2 {; ^1 x% Q4 K5 h */" b* g( p; v& C% P1 ?' Y) M4 J
public DeptVo getOneDept(Integer deptId) {; C- B3 L2 I1 _* V) L4 t/ F$ b
    // 查询部门基础信息/ Y4 E( {! F8 I" B  M. ?* q+ Y
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);8 U3 Q/ g" D- K4 N! r5 }/ N
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
7 Y7 ]; e4 X& h' I. {4 p    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);: N. v) O; v/ L  r5 O  C; M5 O
    return deptVo;9 s# D, i" @  Y6 u
}
) h0 }4 w  M4 d4 M' Z- Q! p% h</code></pre>
7 w, W# w& k/ r5 `* R2 |. f<p>补充附加信息</p>
9 f4 K; J6 S4 O: A( z: |<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
! Z: y* T- ?( q* _. }    // 根据部门deptId查询学生列表
; O: p- h' J- g. ?, P    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
) @7 V0 Z8 R  D& Y    List&lt;User&gt; users = userMapper.selectList(wrapper);2 Z! |8 Y3 t+ \2 H2 y
    deptVo.setUsers(users);; |- R; k: J6 m+ ^; [+ {
}
8 @6 ]' Z7 ~4 }</code></pre>
" s8 w9 c4 G( o6 z5 {, `8 M<h5 id="2理论分析-3">2、理论分析</h5>( O# M! L% N9 d( E" t  D: k) C
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
  \5 a1 @3 k& L- K) `2 e: s) D- N<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>7 h, W8 i" e/ Z. W. L; \
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
1 V/ U$ @& \) |1 ]' `<h5 id="1示例代码-4">1、示例代码</h5>" [, p$ h0 p2 M
<pre><code class="language-java">/**% k5 `% X/ M' ?" Z$ r# n) c4 l
* 查询多个部门(其中一个部门有多个用户)/ d* H. d( h4 ?2 {% ]6 B5 v
*/
: _. E, d: D: ]) U7 {public List&lt;DeptVo&gt; getDeptByList() {
% r! K/ L) I* W+ Q    // 按条件查询部门信息
$ M8 R, W. B' ?7 K1 t0 }    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());, O9 p  q$ I. ^$ L% L- }, A
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
  m& o! d4 ^; w  S" V) S5 u    if (deptVos.size() &gt; 0) {6 r1 M2 Z# m" K+ N
        addUserInfo(deptVos);
" @4 Z, d# @8 _, I4 ]& K    }
, h- P+ w. {! C: A3 p    return deptVos;
& r% L' h/ s$ H' k3 q}2 j4 O  J) B- T1 b) T8 W5 D
</code></pre>
, z+ Z; @) j7 d/ j* y<p>补充附加信息</p>
( [1 \- ?# i' Q* z<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {0 a$ T+ d& a' G' B
    // 准备deptId方便批量查询用户信息) }6 j0 \  U" ?, Y
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
) I" V$ k( e# \* D1 _, V. t6 H) m    // 用批量deptId查询用户信息
! D; z' ]* G6 C/ A$ j1 i4 ~    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));* p3 s9 P$ F+ {9 U& R
    // 重点:将用户按照deptId分组# ?( t" M! L$ \2 S) e
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));& s: U6 O$ P# {$ j% m. X
    // 合并结果,构造Vo,添加集合列表
5 A( w4 e, W. h    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
5 S. q6 \4 m2 j* t8 L: a" l. y}( T6 W( K( Q& u0 D  {8 g
</code></pre>+ O$ J4 [& {; f* v5 M  Z
<h5 id="2理论分析-4">2、理论分析</h5>/ I- k  X2 J8 H" p
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
/ ?4 @' l& a" t2 `$ e: s8 r<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
2 v; p& q# N& Y) I# B; G<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
% |6 K2 W4 h0 Q3 l2 F0 C<h5 id="1示例代码-5">1、示例代码</h5>; Y- J! w4 P* A  X! ~+ e
<pre><code class="language-java">/**
" ]( m- \! }" }! A * 分页查询部门信息(其中一个部门有多个用户)3 ^5 S- V7 L- ?
*/! ^/ F8 l4 M# e4 J% ?+ \" H* r* h
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {/ K3 F5 }" _* D9 x. s: n& ^! h8 k1 s
    // 按条件查询部门信息# M# S) P6 v% D: Q  q
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
9 d, Q. l. k7 \9 v' ?    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
6 _) ]# `' S) x& q# m5 o5 C    if (deptVoPage.getRecords().size() &gt; 0) {5 Z8 Q  o) @, [* |+ j
        addUserInfo(deptVoPage);6 l0 D1 C4 ?, K$ E. Q* O
    }) d  u% A# ~) s) S/ }
    return deptVoPage;
4 t  w" N: L/ g* f/ {}9 k+ ?  r; b7 ^  u
</code></pre>
$ O! b9 J: }3 I) F6 w<p>查询补充信息</p>
" c5 J. R% {  S<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {! i9 z: D$ v7 `2 z/ A
    // 准备deptId方便批量查询用户信息
; d" h6 w  C# y1 |    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());. D6 b- v. o8 w4 c' V- d$ `
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
) @% A2 Q1 T  o6 q- D2 F, c    // 用批量deptId查询用户信息
; u3 D1 j% G) i. V5 e& i    List&lt;User&gt; users = userMapper.selectList(wrapper);" |2 R" O1 v' l0 ]6 _$ J- y7 b( v
    // 重点:将用户按照deptId分组/ ~- m- g5 i2 @! M) x
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
- F) P; O, t4 }! H2 o& n    // 合并结果,构造Vo,添加集合列表# @  l& A9 O1 j2 W
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));7 m* H# u+ z2 d
}3 {' }- a! R; O( i7 {
</code></pre>. k* u% g# v  S/ D
<h5 id="2理论分析-5">2、理论分析</h5>
& m8 j6 p; y4 E; |<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>2 Z+ `7 h- b; n
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>* ?! ]- ?( ?0 X2 ^0 a
<h3 id="四多对多查询">四、多对多查询</h3>) n, S% \. ]+ M' [! B
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
4 ]. g3 |- Y7 n( }: d<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>% X2 U  o! H$ J% ^
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
4 u3 S4 s% N6 ~. }# \; ?  X  s<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
9 s) V% k% q5 U/ H- H<h4 id="一查询单条记录-2">(一)查询单条记录</h4>8 {  {( M2 t& }  w7 W
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
7 J0 z) U: O0 z* f0 }<h5 id="1示例代码-6">1、示例代码</h5>
6 v, E; I# ?* w: U% U<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {  ~% a, r3 s- ?
    // 通过主键查询学生信息
8 X7 v6 l: S# j+ s* j    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
& _. H4 G+ n( ?" G# Q+ {    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);5 h& U, I5 l6 ~' A$ l
    // 查询匹配关系
' J. a/ _+ {9 _2 W' ~    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
9 W4 k  ?- P% ~0 C3 d- l# |    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());( p8 `# n! l& E2 b/ Q
    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
5 u$ C; P$ f( ^2 P) k' D        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
+ x. z( `2 j+ p, i        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
2 e! w$ w6 Y$ ]3 w4 U& a        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
  V2 w; }) Q: m5 }: S% }1 Y        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
& p9 }9 c$ y  `2 ^1 x! I7 q; f0 A        studentVo.setSubList(subBoList);' x! q7 Q7 t& J
    }
% |( B0 L( L# `' M    return studentVo;
1 a" K) q* T, o1 r& G7 E! ^- Q}
# [( o- i8 Y5 _! O</code></pre>4 J- ~/ V9 a" X( a- s
<h5 id="2理论分析-6">2、理论分析</h5>
+ z: Z+ B( h; Z8 ?5 K$ ?. V<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>& P) r' S, h6 @
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>4 X, ^4 [* s% `. h4 u
<h5 id="1示例代码-7">1、示例代码</h5>- x3 g% [. @9 Y" m/ S4 a
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {0 r5 A9 r. O4 D4 J# R
    // 通过主键查询学生信息; O" l4 c2 m7 T" C) L2 `
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
" D* U6 ^1 O; O" N    // 批量查询学生ID
% p  W* m9 N1 A! i! j    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());2 W3 Q6 w, C) v7 O4 H. N% h* e
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);- O$ w# {# @' ?0 _
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
' W, s) H" Q8 `    // 批量查询课程ID
- J4 [: u  u$ V- k    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
# S) |* e7 c9 |/ w    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
/ m3 v1 H( ?' [  s: o  j6 L' O        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);( P) I" f6 P0 e# R) {" f
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
" m( ?& f& g; [8 O. n% y        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);  Q7 D4 {3 l$ J
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));5 v* d0 g5 f) U- {3 f0 M8 D/ u
        for (StudentVo studentVo : studentVoList) {+ [" t# {# u/ v( u& y, a, f' }
            // 获取课程列表
/ V1 ?, y7 `& w2 e- V4 S            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));; O4 b) ?3 a% h* F# s9 H/ h3 H
            // 填充分数
. z- K& e8 S4 M7 A            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
, u3 Q+ M0 q( I( O1 Z% a4 h5 i9 Z            studentVo.setSubList(list);
% a. b& J& e5 Z7 M( [        }! j( J1 N' h* s8 j* p: t
    }/ ]# K; D; J% ?4 v& d% b3 x
    return studentVoList;
+ j7 v7 k: }3 C& N+ c1 |}
" f; r1 S( }+ Y7 U# \</code></pre>
. U, W' c; ^! b+ Q2 {' l1 j" j<h5 id="2理论分析-7">2、理论分析</h5>( P. N1 |2 d! @( O
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
/ e* m8 Q1 N4 a* R+ L<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
# \* t8 M. g  E! O7 }- l<h5 id="1示例代码-8">1、示例代码</h5>* {# L* k" i  n; z9 r# T
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
. Z6 a& _( `, d( m    // 通过主键查询学生信息
8 g7 _3 U4 c# }$ _9 k/ H    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
$ D) S! Q5 c& b/ f  v' T    // 批量查询学生ID# \7 g/ @5 ]1 V/ q# M8 t2 y
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());" W- p# M, C1 C- q+ R: l
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
4 a# r2 t8 N! G( H% _6 H    // 通过学生ID查询课程分数: ]' y7 o5 C: O" h" f7 |- n' L
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
/ I7 Q$ Y% ?1 g7 ?" e: r! b) [: X    // 批量查询课程ID% y( _' \) F: e" {% _+ b
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
' k6 d" Z/ ^+ |* w7 U9 g2 g+ A; R    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {! Q  B' S0 m/ K6 R
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);7 s" U- N+ b( Y$ n6 K5 m
        // 学生ID查询课程ID组
# D" }3 U' t3 o. ^        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));: q, D% [; P* z3 K& P* x/ {

$ a% V. ^3 M! k$ J5 ?* h/ \        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));  [  U1 g4 o6 w+ X& t$ X- R6 w
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
0 C) `' h$ P2 S  Z% b2 e        for (StudentVo studentVo : studentVoPage.getRecords()) {" c1 S0 F' O7 R5 A  c+ |
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));8 |1 G- ?, w3 G- Y$ C3 J, f* h; N
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
2 l, F% z  K" k! V. _6 R, M. e            studentVo.setSubList(list);; E) C; m6 n/ ~1 S* X8 N, `' i! ]9 m
        }
, S% P) v. X2 r+ q6 I, a& C* a; V    }
5 C: G. q  [( Y  N/ [4 j3 }1 ~    return studentVoPage;
& L. t& T% ?0 g, X2 o6 |2 ]5 p& ^}+ @5 j+ o& j4 Q
</code></pre>
; y4 R+ {2 m- H/ i" _' W  K9 b+ `<h5 id="2理论分析-8">2、理论分析</h5>
/ h. N# l- _8 |( A<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
- O$ p* G2 o1 s) p<h3 id="五总结与拓展">五、总结与拓展</h3>2 b, A6 E0 q$ \0 ~, }" O' F
<h4 id="一总结">(一)总结</h4>; y! _6 j; t$ T& L' E3 B3 z
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
1 d0 O& f/ }6 @/ b2 x* i) `<ul>
- T7 Z2 q' }. T<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
9 R/ L) A6 z  ?4 A# ?<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>, n5 J6 m) y; V6 a
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>, `9 e: u0 f; [" Y$ c: R5 _" w5 t
</ul>  A4 l" w  u$ f
<h4 id="二拓展">(二)拓展</h4>" f5 ^6 L0 t1 c& C/ n5 p9 Y
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>0 q& }2 T9 }( s! L: A% w
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
: k: h( T' l# @9 o* i<ul>8 f- R" h8 B: E9 ]/ S& E
<li>当数据量较大时,仍然具有稳定的查询效率</li>/ q& C# Q. T" l6 `7 Q& u
</ul>
: n0 t9 c8 h5 C' m( |0 z8 x<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
, e  r1 A% e! a<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
8 X7 r% X7 r1 X0 o+ j  g' s<ul>
, f  @2 j) @' F7 `: C+ W<li>与二级缓存配合使用进一步提高查询效率</li>% y' O$ A" B! u1 D/ Y  z
</ul>
, k3 H2 N, K) L* c4 @& i<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>  w. ?" h$ r! W0 `/ L8 J
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>9 E# o* A. C% a7 x
# E$ {1 |- K8 {2 m* n6 \7 w
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-8 00:48 , Processed in 0.065578 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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