飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8049

主题

8137

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26477
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式

. J/ v$ N7 T) H" q<h3 id="一序言">一、序言</h3>
4 p5 t" q" A& `5 c( J<h4 id="一背景内容">(一)背景内容</h4>
8 ~6 }3 \2 ?6 d, O<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>9 b0 Q8 ]* D( J: o+ {7 \: N: d- p: \
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
- _" V& V; `/ c- n9 T9 m9 D<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>$ k8 n. T0 _: p' r  q  `
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
2 O2 H& k  @* h- y  D<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
( B* c  g! \# R) a) P<h4 id="二场景说明">(二)场景说明</h4>
: ^2 Y$ e% |* p7 U  \! P4 N<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>+ y% {. g3 q! h8 p) o" E" Y7 U) [
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
' G5 b9 Q  \) Y# Q$ Y! {- r<h4 id="三前期准备">(三)前期准备</h4>8 R+ [/ a# ^+ O# U% H( Q0 c
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>. d0 w! H7 G' `; Z2 J# e
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
0 }  E% P; _1 _1 g<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>$ {# u3 Z  U6 U5 R5 u
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>+ E) s5 U) k% U7 ]5 M: l$ u% O- E
<h3 id="二一对一查询">二、一对一查询</h3>- L& l  V* w# F: ~. |" L2 n2 c
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>- k9 ]6 v8 U7 q4 g' J# {9 P: d1 ?
<h4 id="一查询单条记录">(一)查询单条记录</h4>, s  L$ W, C5 a) i) n9 P
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
0 v% ~- d1 [! t' i<h5 id="1示例代码">1、示例代码</h5>
9 H0 v" h+ M1 Q4 x. l7 g, Z1 i: I6 R$ p<pre><code class="language-java">/**1 W! m; Y0 X) o+ F  k  e+ @
* 查询单个学生信息(一个学生对应一个部门). g0 ?6 F/ }$ i' I' O
*// K; P/ c" b) @8 p1 J- x  E9 V
public UserVo getOneUser(Integer userId) {+ ?- u3 d4 ^4 M% d' q) q
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class); H1 U( h7 B8 q( d! _3 [: K/ a" f& e
        .eq(User::getUserId, userId);# x/ N/ D( n0 U7 n. x' {% y: e
    // 先查询用户信息9 h# A# I8 ]3 N# b+ W
    User user = userMapper.selectOne(wrapper);
) N  L, `% d% d3 b9 w1 V+ P    // 转化为Vo& F( H7 [+ m) d0 g
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);6 V# }7 W+ _: z8 q4 \. s1 f4 z2 Y$ N
    // 从其它表查询信息再封装到Vo& p/ X3 p$ I7 g+ d0 A% a
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
) ]- p# U6 y; z    return userVo;
$ {1 t4 o5 G* o7 C}
- M6 Z+ d7 |4 b/ F' m</code></pre>/ Y0 l5 k3 V0 Y& k) k/ z
<p>附属表信息补充</p>
( Z8 {0 N6 k7 M% _<pre><code class="language-java">/**2 n) M+ y& e6 V( G
* 补充部门名称信息7 n. S  [2 |: r  v* H$ d5 R
*/- X# Q5 [$ r8 S2 W$ {9 {6 Y
private void addDetpNameInfo(UserVo userVo) {  R/ @3 ~  n6 U  B8 p. A: j
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
$ o4 x. l, Q8 I) w        .eq(Dept::getDeptId, userVo.getDeptId());
; E$ c$ K! p, _& s& f1 k    Dept dept = deptMapper.selectOne(wrapper);
* J; W0 |! r+ g  i    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
/ I- W2 w/ c1 m}
# T& c$ V4 t9 s7 q( d$ P' E5 X</code></pre>
  w/ z( R- H) P& l<h5 id="2理论分析">2、理论分析</h5>
0 W7 Y: v0 q, V) _9 L  f<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
$ T- T8 Z2 W. L0 b7 G<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>) X2 q+ v- M& H/ U
<h4 id="二查询多条记录">(二)查询多条记录</h4>' ~: G6 s' b2 j  E5 q- w
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
. k. h6 d; _5 D& ^3 a: D<h5 id="1示例代码-1">1、示例代码</h5>
5 C! K$ ^6 \2 N6 H<pre><code class="language-java">/**2 {  N  v% ~+ c& D, v
* 批量查询学生信息(一个学生对应一个部门)
/ x5 [& ?* ~' b */
+ ]  T  z2 }% s. l8 fpublic List&lt;UserVo&gt; getUserByList() {
* s- v1 c: d- Y  @. @    // 先查询用户信息(表现形式为列表)1 y+ Y& J$ L& y
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());" ^2 u! ~& U" a5 S; a' l
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());' c7 c" q" H: [) y
    // 此步骤可以有多个$ U. w! w4 P' G" Q' h
    addDeptNameInfo(userVos);; V" W; q: U! h/ Z7 s( i9 k1 A
    return userVos;# C) H! Y9 Y" o0 p2 @: I, f
}* I  c; ^; y- I6 Z6 `/ i: w2 b
</code></pre>
( @) x+ E- d! D5 }; ]6 Z<p>附属信息补充</p>
' v7 \3 U7 [" w! F<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {- F+ T5 L1 p  Q! c* y) c9 u
    // 提取用户userId,方便批量查询
' J5 ~' x! v" @- `! I, u    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());, R0 z  C( w4 L4 D# s) ~5 u5 Z' P& _
    // 根据deptId查询deptName(查询前,先做非空判断)
2 F& K. i" a3 e# _. i/ }& q; a9 a    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
5 l+ R, P, z3 r6 F+ C0 _% s) L2 R    // 构造映射关系,方便匹配deptId与deptName; l0 K4 ]. ^6 X* |2 G
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));' E& ?) g( d1 n; l
    // 封装Vo,并添加到集合中(关键内容)
% D$ Q1 F$ @3 @" H5 _    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
" _1 X7 w- n) z% n}
/ H6 E- _% N8 l8 h</code></pre>: a* t2 Z& s$ D' \
<h5 id="2理论分析-1">2、理论分析</h5>
1 s" j/ ~. _$ T6 v+ _<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
! G7 n" _( E! z4 T: k' d% b# B<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
, f1 W$ H2 [3 X: b<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>' o' U7 G$ N1 c6 ?2 U) U7 A
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>, Y- [5 |% H% z
<h5 id="1示例代码-2">1、示例代码</h5>
% O% n) C" D' J<pre><code class="language-java">/**
. {+ v: l- ^4 B  j * 分页查询学生信息(一个学生对应一个部门)$ l( y* {) Z. n; d0 f
*/+ V" j% H- x% X% T) j
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {! V5 A9 E0 `0 w5 J5 `
    // 先查询用户信息
' }9 U, {* C3 c' @  w8 o7 S; s    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());& M; `0 Y$ ~% O$ @
    // 初始化Vo
# K' B" n0 o8 [1 ]    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);' I3 u" T; j: o
    if (userVoPage.getRecords().size() &gt; 0) {9 E5 G( E0 X; D2 n
        addDeptNameInfo(userVoPage);
, P7 C2 g2 ?1 y    }
4 H' ]- G, P/ }! |    return userVoPage;
' `7 I! H: y- J! p/ Y}
0 O" W/ ~1 j8 _</code></pre>
9 q7 }" M+ ^' w$ b7 c8 T$ Q. i<p>查询补充信息</p>
1 x5 v# w. O" q<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {* E6 `3 d. a# J; K. Y+ i
    // 提取用户userId,方便批量查询6 F7 H7 ]# G4 _; r& u
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
: w' r- U+ m( k! o    // 根据deptId查询deptName
2 A/ A, ~- q0 w$ L4 ]    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));2 c6 S( \1 G: b' n; P6 D0 Z
    // 构造映射关系,方便匹配deptId与deptName2 n( j! }* p7 o" X
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
, I* b6 k, I# K4 R& Y# [    // 将查询补充的信息添加到Vo中: G% m. T' e% T& @
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));3 l" j; {# y- X* k7 \
}. w, `( M8 X$ {& ^6 M
</code></pre>9 l/ K1 d& w, V# c- G5 O& \, N9 G7 m
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
4 D: `  ]! M( T/ e<h5 id="2理论分析-2">2、理论分析</h5>
0 L. N( P8 r4 c: h<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>0 l9 R% f9 V1 r: J
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>- A1 \* i" c; u5 B/ g
<h3 id="三一对多查询">三、一对多查询</h3>& p1 I) D$ X- x
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>! _5 N6 W, c. |! v1 \+ V
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>, o+ z1 m" ]: [
<h5 id="1示例代码-3">1、示例代码</h5>
# o$ Q8 |1 Z. v. Q<pre><code class="language-java">/**- t* U5 O( L. s. o
* 查询单个部门(其中一个部门有多个用户)
* N1 x) \5 D! M3 Z9 S- m */
+ D" M5 `, t+ ^! R' B" Gpublic DeptVo getOneDept(Integer deptId) {9 J+ a; y3 I: A/ l! \
    // 查询部门基础信息* N# s# T! h/ i# y3 r* z3 v
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
. i5 \* O& B5 M3 s, ?! I    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);# E8 a& X. L8 K  q
    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
8 Z- B  [, }( P3 Q+ ]    return deptVo;
% `3 X  |; N% h6 t" u- m& B}7 }4 ?. F9 |! }# d
</code></pre>
, `' _) |; _* b5 h<p>补充附加信息</p>
. c/ Q' \, W$ {5 a0 b<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {4 M3 p) Z; h$ p: a2 J  B
    // 根据部门deptId查询学生列表# o1 |1 o" f* u4 U
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());. q4 d! |- y) _- @2 s0 W8 L
    List&lt;User&gt; users = userMapper.selectList(wrapper);
0 X5 S- W" W& [8 d    deptVo.setUsers(users);# @) z  A, T7 N& l- S
}$ z& C, l7 L) p; D5 p- y
</code></pre>
/ ^) ?2 O7 X! _% Z( a  ]<h5 id="2理论分析-3">2、理论分析</h5>
% _. D3 V8 s% a6 X<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>! t; y# T" e% b- S9 j4 {
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
2 t/ H7 F  f( w6 y* R7 ~. ?, ]<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
8 _+ S6 N# p2 U6 P) T: t& `; p<h5 id="1示例代码-4">1、示例代码</h5>
0 D$ z2 q6 L! v/ x  K<pre><code class="language-java">/**! r0 I0 n9 n1 o
* 查询多个部门(其中一个部门有多个用户)7 d$ A0 \, V( N0 ^) _
*/4 M4 z: d/ j* V
public List&lt;DeptVo&gt; getDeptByList() {* h- A9 o- G' @1 j; {& z
    // 按条件查询部门信息9 k1 X6 v/ f/ U, @* {4 i  H8 Q
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());  i, H9 [2 \+ `- t
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
) ^6 O1 o& }, Z0 q4 h1 q0 j; D    if (deptVos.size() &gt; 0) {
, o0 E& t9 C( G; a        addUserInfo(deptVos);
0 V& }% ?; K! a" x  N4 Y    }' t- C( R% C- E! i7 V$ F9 q
    return deptVos;
; g+ e. M4 h# \- P}
0 V0 y& H. J% l2 \( v/ E& K</code></pre>* J# r+ v1 b" p' `5 M$ `* \0 L! U/ N
<p>补充附加信息</p>
# J3 N* ~0 e9 e& a0 S5 l<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {9 j5 F+ ?/ v9 H8 S# y
    // 准备deptId方便批量查询用户信息
3 X6 U) r/ y0 L7 W    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
0 I) c, ^- A2 I" ]% x    // 用批量deptId查询用户信息
0 r: W# D$ z6 P0 g6 p: C* ?! x# Q    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
; Z& x) R" ^1 ^. j8 S    // 重点:将用户按照deptId分组0 k" q- Z% f1 t% o
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
1 u& w6 z7 @0 i& o8 E5 \    // 合并结果,构造Vo,添加集合列表, x/ a( i5 [# K/ Z3 G# d
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));) V" |, ]1 G& w- L) B: d8 w
}$ h+ x: k$ B7 G' ^* o
</code></pre>
9 |* A/ |- ]( M0 q# i<h5 id="2理论分析-4">2、理论分析</h5>, Z6 o) M; {, P0 k) N+ ^
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
/ h3 v) @7 J, v  d/ J6 I8 j6 L8 h; O1 L<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>0 T* r8 Y" g8 x
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
2 f9 C1 i# G8 G<h5 id="1示例代码-5">1、示例代码</h5>1 t; f) U* v& |( i9 J
<pre><code class="language-java">/**) z* g: S+ f2 J) D& ]/ u
* 分页查询部门信息(其中一个部门有多个用户)
# d- l# M- K1 s6 y6 C5 c0 P8 N */
( o8 U4 E& d6 @- S! T3 Ipublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
- x" I) O3 Y+ U    // 按条件查询部门信息% g9 F( t% u2 w' \
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());# V% w. p5 X- B& k3 R
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
$ u8 |2 `8 S6 F& `" P% S  j" X: u    if (deptVoPage.getRecords().size() &gt; 0) {
+ N1 b3 g6 I6 W& y. A! M$ A+ V        addUserInfo(deptVoPage);
2 s  k0 ?6 }% G0 L9 k+ L    }
0 N& q# M! ~' l& P+ F% [2 S    return deptVoPage;1 I- f: h8 _: B; s$ j* h
}
* R; h6 N$ ^( O! r</code></pre>% e( L7 h4 m5 {' J6 X% E
<p>查询补充信息</p>
+ X1 ?) Q& X1 d! _8 j! F4 L<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
9 c- n' p! G- }3 M: @% ]3 r2 N, r    // 准备deptId方便批量查询用户信息
- o/ ?7 X, I/ i# i    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
% ^, H+ \) n: t/ `; y  L6 K    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
/ Y- t$ _) }& j    // 用批量deptId查询用户信息2 X, ^! j2 ~4 a9 S( [9 u
    List&lt;User&gt; users = userMapper.selectList(wrapper);
$ O$ M5 J, A) S- [' ~) v- b    // 重点:将用户按照deptId分组
" v3 |& C8 y, @; v    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
; V6 X+ h" [* K0 |, F0 @8 [    // 合并结果,构造Vo,添加集合列表
7 A2 [+ \9 s) L- i    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
9 j+ B) D7 p5 R}
7 q2 `! f3 d& E$ E2 i" J- p9 A</code></pre>/ t1 v9 p: L4 V# w  Z6 Q
<h5 id="2理论分析-5">2、理论分析</h5>
: f5 H3 v+ @. f<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
! @- x" j. f$ J9 y<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>; v. E" R+ {: Q1 p* v1 O
<h3 id="四多对多查询">四、多对多查询</h3>4 X$ K# J$ q! P! [  r
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
1 x# m3 V0 m; {! k<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
9 B0 n+ |$ {0 C2 c, a<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
9 W, d. e: r  X: Q6 K! t<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
- P6 D( v6 s0 q6 L# y<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
3 e- x& V, o. P) ^<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>6 o1 Q( l0 F4 H; P) Q2 _
<h5 id="1示例代码-6">1、示例代码</h5>6 A7 q, v$ q# G4 t) E  G, c
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {5 G6 x2 \9 S4 m7 L3 T( y" E- z
    // 通过主键查询学生信息
+ H/ e0 k6 ~( ]& R! P+ y) ]8 A. v7 A    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);! j: k; x# C& ^# m4 v9 u
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
7 B& O2 h+ F4 D' [1 r    // 查询匹配关系) {) U# v) e2 V' z
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
9 Z3 a7 B$ @; ]- G8 m+ [7 ~    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
$ A% B& x# [( L2 p! a2 B    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {0 v+ y0 N5 {; S; \  j
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
, @, `$ m" m9 T) y  P9 A3 m        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
( H1 C9 v! K* p" J! A* J0 o5 w) ^        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
2 s5 k% X4 s: l. `* [3 O* g        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));! f  E; K' n+ ^& [8 X3 w+ T* ]4 K
        studentVo.setSubList(subBoList);) d( M8 P. c( Z  e2 c
    }- o% n' g; q3 u0 j7 H
    return studentVo;
) i9 b! L2 @, @}
2 x7 \4 Q- m5 R0 D! t  |( m& S6 K</code></pre>
- t6 ~  u. d: S# w8 w2 \<h5 id="2理论分析-6">2、理论分析</h5>6 N- Y& Y8 @1 Y: a) t+ U1 L- r. d9 {' G* T
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>% H! ?* A. e) k- i9 P; {+ d. q  J2 y! \
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
, U. _6 m; D9 O5 R! t<h5 id="1示例代码-7">1、示例代码</h5>& G: f) H( ~+ W/ ^
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
3 Z1 ]0 v" {  M& A5 E, a, X) R    // 通过主键查询学生信息
; E2 z7 K9 K! H0 r6 ]    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
$ M; [, f4 t" Q7 }$ v* i    // 批量查询学生ID
. f2 h( f" b7 \2 j' _    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
+ _0 B4 u) T  ^$ v    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
9 L* R* ]- t4 _" Q. c9 J" _( J, C    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
& r/ k0 r. u& s% Y* |( P    // 批量查询课程ID" l* X5 |5 G! X$ r1 B
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());" K$ ?, M, {; k* k  l
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {5 ]9 r$ f6 |  d- H
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);) ]' `9 G2 K( u9 S+ v- S$ c
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
4 y5 g- r3 g6 [- o        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
% ]: x" A: J) j6 e. D# Q; }( S        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
% b" Z8 |! O( L! t* i/ Q        for (StudentVo studentVo : studentVoList) {
0 m; n6 c# [8 ?0 v' J7 Q! R) @            // 获取课程列表, M' i) M8 \9 i" p) l0 J
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));" g5 P$ F6 s% C$ g
            // 填充分数
! L0 g' o( Y: F& T9 U/ n            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));( F7 [$ L# k! K! s
            studentVo.setSubList(list);
7 i' {$ m1 F" X0 b7 ^/ \+ o9 _        }
; \6 P$ z. |' d1 s7 P3 b! e/ J    }
! ~* ^) g* L* i+ ]3 T    return studentVoList;
/ e" U1 `7 O' m+ Q6 b8 a  p4 g/ u1 c}
5 r% t( [4 d4 k  O# k</code></pre>) m7 \% {2 y2 a: g& B
<h5 id="2理论分析-7">2、理论分析</h5>  C) R7 L' W, O& B; P  r
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>1 |. z8 a( v& W* S. t
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
' N8 m. I8 i* r: v) \, ?1 O3 w<h5 id="1示例代码-8">1、示例代码</h5>: a# |5 \  M$ V/ h- j' _
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {% ~" Y( q! c( h$ z$ d& W
    // 通过主键查询学生信息
3 p" ~. Y! D- _# t- |2 T$ p    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
. ^6 @" h* q+ B4 {  v    // 批量查询学生ID: C1 n1 S# J* i6 g) U7 P
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());( ?' |5 ^- N5 T
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);/ r5 T. e$ t0 T8 ~* q) l1 A
    // 通过学生ID查询课程分数
' U( y  _, v: d% T; @$ Q- |    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
. L& K8 q5 ]7 q    // 批量查询课程ID. d  y0 k$ v) ~
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());3 n! l7 e: q) ]+ u. [
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {2 u/ }& v. _$ @9 Z' S
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);) L/ B: i, K# Y0 m- |2 ^
        // 学生ID查询课程ID组$ Y  n. w0 I8 R3 ]! \5 ]
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));! w9 i; k! w! ]; N1 s2 |- I

5 J. r5 |9 \2 D' w# K2 l        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
3 d% t' ]& k/ a+ r  a( |: T        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);4 A7 G, M. M6 c5 g
        for (StudentVo studentVo : studentVoPage.getRecords()) {4 L# `  R$ f7 ^! ~# b
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
+ H* H% L' X: U3 O4 ~            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
+ R( N! ~1 R* W) |0 J/ k7 u            studentVo.setSubList(list);
+ ]* J3 o% }$ o9 n: _% A9 R        }0 M/ h+ B: C' f5 E9 g) ^
    }& \, [" Y: V: z' `  U
    return studentVoPage;$ R0 _( P" o7 r1 W
}
; H% ?# ]2 G- e1 G/ C1 h) ^</code></pre>& z7 g  D- D( |! q: a- z. w
<h5 id="2理论分析-8">2、理论分析</h5>
0 k" v% l% j7 e6 B) |$ p<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
: C  |7 A% V$ \) L<h3 id="五总结与拓展">五、总结与拓展</h3>
1 X+ V: \. w0 A' Z<h4 id="一总结">(一)总结</h4>
* t& Q( a  ?+ ]/ ~+ ^& I<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
  O% D2 Z. ]4 R" l* [<ul>
% ~! O( Q% p# H<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>7 ~4 g# l( T1 R6 W1 \3 h3 s9 X( _
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
" k7 ?+ p* H& F$ j6 V5 c<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>$ W$ e2 C' N6 x/ q3 E
</ul>. f% P2 w6 h/ [6 c( F5 k
<h4 id="二拓展">(二)拓展</h4>' Z& O0 \% Q  ^+ ~3 W
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>2 A! F$ _3 X9 t, m$ x. z
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>' y- z' S" C: m2 |+ F; x
<ul>5 w5 q2 I( i& d. L3 ]9 r5 E' X
<li>当数据量较大时,仍然具有稳定的查询效率</li>" e/ S2 h1 m, s' g+ ]
</ul>
4 q4 O, h# Y+ W<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>5 E6 c2 q7 P; ^  Z2 o" `
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>8 d7 x/ q. x$ C- R! {0 ]" ?
<ul>! d. ~! r( A2 I6 |7 L7 ?5 {/ e
<li>与二级缓存配合使用进一步提高查询效率</li>/ B2 o! ^$ p6 P! O9 ?- u/ r, B' T6 v
</ul>4 `2 W$ v3 j" G4 O
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>* x2 a9 u9 G9 z: v0 m- m
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
6 e: i# F# ?6 |# H$ m7 d6 h/ d9 V" V2 n' }
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-10 12:50 , Processed in 0.073923 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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