飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8038

主题

8126

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26444
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
3 B  D4 L$ f; V4 m0 `0 q
<h3 id="一序言">一、序言</h3>
9 }) f5 Z6 A: Y2 A% E<h4 id="一背景内容">(一)背景内容</h4>: |$ l% ~- r3 \7 I0 Z! f
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
8 l6 p2 L4 S7 o* i<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
3 R) t- ]$ W- b) a8 w: Y! G  w+ H<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>: c2 c8 J7 z8 i* ]
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>/ p' j$ i: o/ _5 d$ z
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >1 h8 i: U1 c- i. `6 ~' z+ Q
<h4 id="二场景说明">(二)场景说明</h4>  K4 l  n  s. }- h/ R1 c
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
+ U3 L6 l3 B2 x! t* b* U! I" S<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
% ?, p  ]1 B/ J, K1 p* J. X1 I" j<h4 id="三前期准备">(三)前期准备</h4>
, U, N% C" _- ^( E$ t<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
0 R# n+ ?7 y9 Q6 r8 M<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
3 G- N  A" U# k4 Q<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>' J. ^2 r% [9 Z! j
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
7 t! K$ A' Q- ]0 i. q<h3 id="二一对一查询">二、一对一查询</h3>. X' Z) r. w& W7 E' U1 W" _8 _
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>7 e: L" m$ l" o* M7 |& \
<h4 id="一查询单条记录">(一)查询单条记录</h4>
$ H2 ~1 ~  G$ t<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
) @, `" ^* {. L3 O5 C7 V<h5 id="1示例代码">1、示例代码</h5>
5 h! M( ~( p. b8 `<pre><code class="language-java">/**; v/ T2 I* p1 ?. l# z1 `
* 查询单个学生信息(一个学生对应一个部门)0 Y, @" w+ t! V2 L
*/
* d4 D0 ~0 O+ d/ ?- u+ q( gpublic UserVo getOneUser(Integer userId) {) Z/ R- ]2 H3 v. K
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
4 `/ m$ V* e0 B4 ~3 \% o" r        .eq(User::getUserId, userId);
9 \$ {4 V% H9 D" A2 b' ?9 K    // 先查询用户信息
& e# u1 e" o$ N3 N5 t9 O$ H( D. k% _    User user = userMapper.selectOne(wrapper);
* ~1 M3 q& H$ l5 m- e! H    // 转化为Vo
7 a& Y4 z7 Y, c. H    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);  F$ }1 L9 G6 }! V0 L: D
    // 从其它表查询信息再封装到Vo! Q0 o. ^0 w# s, m: I; G4 o; q
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);6 ]6 H% {. Q( Z" Z0 L" Y: u/ u( R' r
    return userVo;+ K& m! w) t- S: ~$ A/ `/ J
}' o9 L4 Q( \6 b, ]1 }9 ?' M9 h* t$ T
</code></pre>
/ k, t# j% [' ?8 O<p>附属表信息补充</p>
: k+ Y$ W2 P  a<pre><code class="language-java">/**4 t7 M9 Q; O* ]& o1 J
* 补充部门名称信息: |2 V. p  `- Y0 a* Q, U: ]$ u
*/; _8 l( I, s1 \; p
private void addDetpNameInfo(UserVo userVo) {( z) m8 z  n/ u& T) i  e
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
' |- _' ], t3 g2 p% j: F4 E        .eq(Dept::getDeptId, userVo.getDeptId());
6 G+ U! T2 W) |" o4 |    Dept dept = deptMapper.selectOne(wrapper);
" r9 ?. g0 r% `. P% Y' \    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
4 M5 m+ M4 H/ ?" h# y' k, y) ?+ X$ f}
2 p$ t  b2 `5 i0 ~</code></pre>
6 S: h  T+ ]/ j) n, U" s% ?<h5 id="2理论分析">2、理论分析</h5>
& ]2 F: \& k/ c& `) ?<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>0 V% I( c( v5 u8 ^
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>% U1 n$ W2 ^  I( v& Q7 f$ j. Z
<h4 id="二查询多条记录">(二)查询多条记录</h4>$ x; L! k  H+ r6 N7 X6 x2 e8 Z1 f0 z
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>7 h, Z( k/ Q/ p) n" j
<h5 id="1示例代码-1">1、示例代码</h5>/ |' \0 ]* A! ]( C) U. c+ U
<pre><code class="language-java">/**6 J& K: a/ M% z2 G% h
* 批量查询学生信息(一个学生对应一个部门): D/ \$ @8 K- g, J" }+ M, E; u
*/
+ I/ m- Y! ^$ y& w1 s2 N6 Wpublic List&lt;UserVo&gt; getUserByList() {
4 S& f2 n& o% J2 c    // 先查询用户信息(表现形式为列表)& T& [2 D# K' t" R
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());5 W3 ~4 s, Z; W- i4 c
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());; O$ E+ d5 i9 }2 U) }/ e
    // 此步骤可以有多个6 P# Q. M7 a1 ~! _! U
    addDeptNameInfo(userVos);
( ]1 J: U, C: d" i, C) P+ m    return userVos;' i5 l$ e# S. p5 Z; `! i" w& C' {
}  R2 M7 L" p! D6 g
</code></pre>. d0 S$ t& l" }
<p>附属信息补充</p>3 w/ [1 D4 F# t6 D7 ~6 H
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {7 J1 Z0 j( f* a! i
    // 提取用户userId,方便批量查询! {, w$ S2 A: [  f! s2 }
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());& o8 t: L8 q( K2 N- d# E
    // 根据deptId查询deptName(查询前,先做非空判断)( @; B' h* R1 k
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
4 q7 \- Y4 E# l% B7 V2 K7 y/ ^/ b    // 构造映射关系,方便匹配deptId与deptName
8 x6 \( c2 k; _. |6 T! _! j    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));& c7 o$ C% p5 d% t
    // 封装Vo,并添加到集合中(关键内容)1 z2 v& P$ K, D8 V7 z$ Y( E7 n5 o
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));/ N& ^, k1 C, w1 R" X: w) Q. @
}
, `" ]2 l. H2 T0 |9 b* L4 k3 s- o" u</code></pre>
; [( e; }0 `- {- G! r7 U<h5 id="2理论分析-1">2、理论分析</h5>2 \' I% ]3 N' C; d& m
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
: u2 c$ b7 e$ U<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>6 t. J( [2 [2 L
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
" y2 t+ l' k# }<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>- n# R: Y5 h- {' L8 J- j" l
<h5 id="1示例代码-2">1、示例代码</h5>( p1 s! A8 m) }! k6 a2 l5 {- x
<pre><code class="language-java">/**  z9 A! B/ j& u
* 分页查询学生信息(一个学生对应一个部门)- x6 T" v0 J# @6 ]  i0 Z5 u1 M
*/4 }* q. R0 @% q0 H7 P& O0 B
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
& o! a( _8 h. M. i  k6 M3 D    // 先查询用户信息8 b/ v; ~( u$ K/ o9 v2 u5 y
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());( N& O3 Y% l2 e& n7 S
    // 初始化Vo
& N, Q0 e5 _6 G, k    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
: g* M: A3 _% z6 r    if (userVoPage.getRecords().size() &gt; 0) {
: ?! W$ b! [2 s/ [. R5 [        addDeptNameInfo(userVoPage);: V. Z4 V) p- U5 i
    }
8 R1 h0 B3 F7 d9 r# N. N6 W    return userVoPage;
5 x4 h( Q+ r' R& w8 b* b}& m* I) p( P5 ~2 N! p
</code></pre>
5 q* |1 w8 w6 q& s. a, D) U+ ^<p>查询补充信息</p>
6 y. m2 C) U$ M8 C* T<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {$ q- R6 B) R; I# P5 Y* u
    // 提取用户userId,方便批量查询
2 g7 T3 J) P3 [- u7 W6 s    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());: p- b' \! v& L$ }
    // 根据deptId查询deptName2 J0 H8 }, p1 O
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));/ J. x3 j0 }  Z' r: r6 b
    // 构造映射关系,方便匹配deptId与deptName
6 `( p% M- l+ `5 N1 K6 I$ n" N    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
. n- j. o, ^% B& @    // 将查询补充的信息添加到Vo中
; P, R2 @: \. S& [2 P, I    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
( c" X% j7 J) n1 A}
- S5 w- z' g$ d4 Q& a& x# f: K; A</code></pre>
3 r& O1 q2 I5 X1 s  v- U6 {! p<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
+ U  j7 c- c- q+ N9 \<h5 id="2理论分析-2">2、理论分析</h5>( Q3 b$ |6 Y: L$ r% q( ]
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>; e8 z0 w- S; |* X
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>: E& j+ g& q5 W$ j
<h3 id="三一对多查询">三、一对多查询</h3>2 n1 T9 j: W% {- ]! x) X
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
6 W3 \& a6 E* Z<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
( z; y6 @$ w. l5 n  s<h5 id="1示例代码-3">1、示例代码</h5>
, I& b0 d$ f# _# r9 J- c9 E3 F<pre><code class="language-java">/**+ R5 {. L" B( V: I
* 查询单个部门(其中一个部门有多个用户)' G! F, a1 t: U0 c* V
*/
% C) o8 a' z* h7 I' a% }; xpublic DeptVo getOneDept(Integer deptId) {
# m2 ]7 Z% C9 D8 ~    // 查询部门基础信息- B3 W8 b& D- u. i) g) W
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);4 I' ~2 O8 j- N: M" ?2 N. Z
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
& [; I1 c* [  b2 g6 b# O1 ~9 h" G    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);8 L0 h) h* v& E" X: d
    return deptVo;
# A  {7 x( m3 c}2 p' T9 P, ?) M/ ~3 N' S% _# e2 {3 h
</code></pre>
4 q1 D' a/ n- G/ t<p>补充附加信息</p>
) s' r, {' h( c2 J5 i7 o' Z; V% W<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {; H4 i8 B6 p  n
    // 根据部门deptId查询学生列表
) W! w9 [* @  V! e1 d* c    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
% D6 x( P/ X  W7 E    List&lt;User&gt; users = userMapper.selectList(wrapper);7 `/ s& F& V1 M4 s+ r0 ~
    deptVo.setUsers(users);
2 U' }& _' v; T}" k4 T: u3 l3 I4 |8 d& P2 k5 n1 N
</code></pre>/ _7 w* X  P+ \7 e& _
<h5 id="2理论分析-3">2、理论分析</h5>
. f3 A2 ~2 Z3 {0 z<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
/ G: x. Z# B- H# C5 x, q<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
9 `5 `& Q8 t: \0 k6 ]8 E<h4 id="二查询多条记录-1">(二)查询多条记录</h4>4 a" c/ q5 l' z
<h5 id="1示例代码-4">1、示例代码</h5>
2 Q6 J+ b# [3 i& M<pre><code class="language-java">/**1 t' h5 S! b6 a, e% i
* 查询多个部门(其中一个部门有多个用户)$ O6 q7 ~: n3 r0 x' Q4 u( _4 h
*/( |! l" i& i1 z+ K
public List&lt;DeptVo&gt; getDeptByList() {$ _: ~1 R3 j; M) _% Q8 Z
    // 按条件查询部门信息
  b+ O4 J- C  `4 G1 Q' K    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
. {: h# g7 U8 N# D' R    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
8 A: R3 Q* A- Z, M8 ]1 g    if (deptVos.size() &gt; 0) {8 L5 e7 G7 A9 {! M
        addUserInfo(deptVos);- [% _- o& `, E4 ~
    }. e8 `1 R) m, Z5 x' m
    return deptVos;
: V7 D+ ~  x/ ?2 ~( i}
8 v& B) n& _' s2 J</code></pre>
3 `  [) d( p# u/ i# q<p>补充附加信息</p>6 \$ S0 S, d. t0 E  e
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
1 |- g9 G( j! i4 [. ]    // 准备deptId方便批量查询用户信息
+ s5 g* p- E$ y8 @6 j8 X6 H! e    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());# M( E" P. F" k* m
    // 用批量deptId查询用户信息
& @" Q7 {- B6 q" _    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
6 N0 g$ q$ o4 R1 k" x1 R+ n! N    // 重点:将用户按照deptId分组
6 P3 X: l% s: S    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
7 o4 V1 |! Y, t" J  u    // 合并结果,构造Vo,添加集合列表* J2 \' D) _' O' j3 ]) v, ]
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));0 ^8 B0 K3 X1 F  A9 A$ D! y$ K
}5 o% J% ^3 F  a: n. l% I
</code></pre>7 t# m" W# M0 V; V2 n
<h5 id="2理论分析-4">2、理论分析</h5>) N+ Y- K. S- w/ N9 r- {& B5 H
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>% Z8 e0 X9 |4 h1 ?! F2 |
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
% r) |4 y3 h+ {: y# ^8 ~% b<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>; y5 p' a4 X% G
<h5 id="1示例代码-5">1、示例代码</h5>
6 S3 E2 Z" T6 ]% ~4 s<pre><code class="language-java">/**
! P! i' T2 F; M% c- c/ d * 分页查询部门信息(其中一个部门有多个用户)
% h  |- x( b5 Q. X  f *// ?" a& p& ?* }7 X
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {7 J! d- D7 K6 v1 ]/ X& T# F
    // 按条件查询部门信息
' K' ^( m* K  d4 u' v    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());$ c* h7 R% x8 a
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);8 }' N# ?/ k/ I1 I9 H
    if (deptVoPage.getRecords().size() &gt; 0) {, O0 b3 _- [. T' z; C% a! J  W
        addUserInfo(deptVoPage);" N( ~7 r: K: V  c
    }
- V) P( a9 ]: ^+ l    return deptVoPage;8 P% L4 s" _: c# d" u: ~9 p* j
}
9 t7 z/ q' D* Y# }2 @</code></pre>
0 a% c- J1 K0 W" `<p>查询补充信息</p>
4 h# ]$ L! o' s/ |: Z<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {3 ]4 b8 Q$ _# g& W( Y
    // 准备deptId方便批量查询用户信息
9 i% _. b& h4 s5 _! Y    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
; ~% @0 v4 g* O    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);/ N% `/ g& p0 E  H, g
    // 用批量deptId查询用户信息3 M2 k* s& C6 r/ Y( j
    List&lt;User&gt; users = userMapper.selectList(wrapper);
6 r* S6 S. o3 |# p( W    // 重点:将用户按照deptId分组, O8 E# S7 O" P3 _6 o# J. D
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));, t- H% l6 g: c2 Q! I
    // 合并结果,构造Vo,添加集合列表6 R! X2 a' q7 W# j: B3 R4 ^( s8 i
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));: ]0 L1 l% G: t: ~: |4 V
}* p  U! F0 |. Y! B3 t9 w
</code></pre>
. B2 N, s- V& x+ V: L<h5 id="2理论分析-5">2、理论分析</h5>
3 N( e5 Q  e4 \4 |# w<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>8 s$ ~+ x9 i2 q! b
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>9 X8 N  M' A. @& \( v# W% ~
<h3 id="四多对多查询">四、多对多查询</h3>
( G+ O' x1 Q) J; h+ D<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
: s6 m" @$ a0 v9 N2 r/ c! _: x<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
# {3 f; @) f# ]2 R$ |5 ?, ^7 K<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>1 Q: Y- B' T! b  ~: o
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
4 U3 M( s! J4 g' m) |<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
( [+ Z0 A9 i" f3 R- c' R<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>  U( E0 e" j" K$ x& G0 [
<h5 id="1示例代码-6">1、示例代码</h5>0 W8 g& }+ g$ U
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {, K7 v  X7 L2 j
    // 通过主键查询学生信息
% x' y( `+ W7 o7 H    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
" N6 D0 g- }0 N1 W0 V; ^    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
$ l! f2 M. R# h. O! [    // 查询匹配关系
. B+ X4 H8 N1 b    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);- j1 m; V1 Z- p. |' h# P6 X9 j
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
4 @; |. F: i2 }7 p    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {% X3 Z# O, ?! A
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
0 C. ]5 X0 ~8 y7 {5 D! l        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);3 M% r+ U9 {/ n6 q/ A4 [
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
: s" x5 j  a+ @2 a2 V6 W$ T: F        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
3 B7 h7 r* I, }        studentVo.setSubList(subBoList);7 b% t+ A% U  q) r
    }
7 O: ?  V) |' r' [    return studentVo;
0 l$ s9 l1 t8 B2 [" S6 @}
, u" Y; u: I1 G. D8 K</code></pre>
  L5 d; l( C- |0 H7 |5 c% [<h5 id="2理论分析-6">2、理论分析</h5>0 n( H, ]6 T8 n2 I' x2 Y1 \
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p># c$ S, m. L9 B3 O. A
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>& \, d0 F# m2 N& O" J
<h5 id="1示例代码-7">1、示例代码</h5>
; ]' Q$ l. X: q' l9 u; D<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {  }" O  Q5 q1 g, k$ l% U
    // 通过主键查询学生信息
+ k$ A5 w$ q4 s4 U3 \, [7 k) c& _4 v    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
# h' y; ]: u* `& L+ C5 K    // 批量查询学生ID/ v+ ?8 Q0 g- h: ]
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());# V* |$ S% v( T2 C' s
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
# r- y- G: i% p$ S6 |% g    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);' U; I* e% `2 E( ?7 S+ g. r0 U
    // 批量查询课程ID
; g) z! ?% H0 E+ Q  ?9 K    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());& p* v$ \, H, o1 N' [( S( U
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {; g0 G; }$ g- p' s5 ]9 W/ Y
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
* i; a: ~; K2 Y* j+ T8 M* t        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
+ i! a+ x2 ~" s& i6 h" w; F) p; w        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
  C  y9 d' }8 v! e7 x        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
* M. ]0 q( l! J, _        for (StudentVo studentVo : studentVoList) {
6 E& X/ V) n. o3 k            // 获取课程列表+ v1 n7 b6 x6 t
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
' @/ S; F2 N# u. @4 }4 K            // 填充分数/ |4 e4 M) F5 V7 h  g+ m, c! K
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
( J9 ?: r# v4 k% E            studentVo.setSubList(list);, v4 {, K, u* j9 K2 `2 g
        }
7 l- E9 q8 R5 }4 W, v( R    }; c1 h& X  {% c! h! g4 _
    return studentVoList;8 {1 o7 j4 D6 p" \
}; ^' b% l/ H5 x! ^3 @, f/ a" o
</code></pre>6 i! B1 o: B, x7 D) l9 s: J9 o
<h5 id="2理论分析-7">2、理论分析</h5>: ]2 t+ U( k8 R+ d% e4 B
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>7 e* K3 F$ [7 E+ M% g
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>+ y; d, f" B* T' M" |: R3 g- B. X
<h5 id="1示例代码-8">1、示例代码</h5>
; ?% F& u( ?* \- A7 j<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
5 g) X7 i4 H# |, Z    // 通过主键查询学生信息) M- l- ^( w& g
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
- A+ o3 R% K% q, k# ?; w; H: g; G    // 批量查询学生ID; r9 u2 j$ X1 W$ y0 u: f
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());' `; z, p( d" Z/ W! W  q
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);+ }# s" s- f- U' A
    // 通过学生ID查询课程分数
9 C  U5 _6 M& s/ L4 X; {+ `    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);$ N& r3 j( j; J$ K( Y( A
    // 批量查询课程ID
9 j  U1 l0 _% F2 V    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
# A# b& L7 v# l7 l8 J    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {, N9 h% y' e! [, ?: l
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);7 ~! y! U1 o- V4 ~4 Q. O+ ]
        // 学生ID查询课程ID组
* M  ^, m6 M, I2 O+ O        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
$ r, a* M$ K& I  h% U1 F5 ?4 }6 Z5 `& `4 ~
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));! Z" N& |! v$ l# b) H. M$ ^5 t# b
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
4 f. ~4 X, K* z% R  c5 G( m0 M5 `        for (StudentVo studentVo : studentVoPage.getRecords()) {
& p* R# O+ M! d% |            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
9 I, C$ ]( ?2 J6 {# k            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
8 @" |8 j& o" d9 ]. i/ G9 r1 r            studentVo.setSubList(list);
3 o+ W! Z: i3 |) C' B2 v1 ~        }# F/ j$ q3 {9 D( X
    }
+ \2 u. N; B) T. X    return studentVoPage;' o+ S4 u2 g, w* T* @, m
}- e& Z0 [4 y2 C6 ]* F! d$ f! `& F
</code></pre>( \, F2 q, c9 A, g0 Q& N
<h5 id="2理论分析-8">2、理论分析</h5>! S; Q6 J4 a+ @7 F
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
' l2 D2 O6 L0 m7 g" u# `* M9 D<h3 id="五总结与拓展">五、总结与拓展</h3>; p' ?, g+ p3 K! O- S$ |& Z
<h4 id="一总结">(一)总结</h4>' O: X* ~: K, J/ V& n
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>) c6 f* @  f" l" r
<ul>- C' Q0 n# c3 ]
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>% T. q+ Z: R; d
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
, I! O5 `7 B+ @( w8 ?  M<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
- v4 i( Q- d: D9 g: w% j. L6 ~8 [</ul>% |" ~4 `; {* c0 p! I( a* w- ^% a
<h4 id="二拓展">(二)拓展</h4>* g, `5 D  o5 s  W" }) f' i
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
7 F6 j- n& V3 ~1 d8 {) S<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>% [$ E3 d. z! K3 F4 O2 o( a
<ul>+ F7 v9 M$ J0 P) O' W- t
<li>当数据量较大时,仍然具有稳定的查询效率</li>
' W6 l+ H2 m8 Q( c0 c</ul>
3 \7 t, a, ~( t/ e# N- M<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
* v) x7 j8 B: R( X<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
# D% M; D1 v: O% l* g: m+ [) Z: ?4 o<ul>0 ~! _1 \* {4 E) O6 {/ g
<li>与二级缓存配合使用进一步提高查询效率</li>
" h( z# h5 E  M1 ^& y8 @$ i3 s</ul>
6 }. U; k, D) S  a+ w; {# G<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>+ z! N6 Z  q1 z( |- W% m
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
+ K0 S- c/ a2 |
; ~" D* Y- w; d+ y' ]
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-5 14:07 , Processed in 0.072321 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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