飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8242

主题

8330

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

# q, i" S7 Q2 |9 j7 E6 n<h3 id="一序言">一、序言</h3>
" p& A, }  ^: s- u" q" R  ~, o<h4 id="一背景内容">(一)背景内容</h4>8 X0 _# ^! b$ p# G0 }; _
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
. Q+ l7 k( n0 T: x: [- T<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>. u) q! ^5 T* @3 u( _9 m  ?; C+ x
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
! |0 J6 O/ y- H4 a6 j6 |<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>( `4 J: F9 W# p# [$ l" e  [( f" `
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
" o$ \# A( e% f. |) k/ `<h4 id="二场景说明">(二)场景说明</h4>" P% K4 E* b# Y+ w- q
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>7 \3 P* X* u& z7 ~% a
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
+ k" p2 U) j/ v* G<h4 id="三前期准备">(三)前期准备</h4>7 D. G( v# h9 i/ R1 W
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
' g; r  Q: G% a( @1 x# B<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
4 @+ ^$ I" E) c9 a' r1 c) b<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>- f& v- E( ~+ w+ E/ @
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
" k& g6 s, F  s. F<h3 id="二一对一查询">二、一对一查询</h3>. h8 Q  ?0 e  ^# ]
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
4 W1 K0 P3 G' D# x<h4 id="一查询单条记录">(一)查询单条记录</h4>6 w; K; ]& N& s  R0 t. _' B
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
2 o3 g' R+ B5 Y; t/ V<h5 id="1示例代码">1、示例代码</h5>- ]6 M8 c  L3 Q
<pre><code class="language-java">/**; r' C# X; b( y4 [" _$ n
* 查询单个学生信息(一个学生对应一个部门)& \# ]9 H, m# P. N+ X5 w) Y
*/
1 o+ c2 G3 Q2 p1 D7 [+ Wpublic UserVo getOneUser(Integer userId) {
* x2 c6 G: O- ?+ ]9 h6 V! i    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class): z; a1 v* n$ G4 w/ T6 z1 w! \
        .eq(User::getUserId, userId);
- r) A$ f0 ^1 R  f6 y1 `* }    // 先查询用户信息- S9 \% C( p1 n( v6 G
    User user = userMapper.selectOne(wrapper);2 e$ t( ^0 a: q1 e' p
    // 转化为Vo
# Z  z! ?: t( B    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
/ ?0 M0 y/ \  M& e# \! z; L! w& W    // 从其它表查询信息再封装到Vo
. }" P2 X% ^9 K- _5 M& e5 x    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
$ `! e8 m9 B! {2 X/ U( G    return userVo;
2 {2 m; R; D, n0 G}
+ m& \3 i9 E- m: u  x# _& P</code></pre>4 k% u7 k7 o8 _
<p>附属表信息补充</p>
  N& b. U9 p% n  y<pre><code class="language-java">/**
0 M; w. A3 M, ?5 u+ c. b * 补充部门名称信息$ r2 }& \$ I7 T2 n0 j0 a( V; P% @
*/
+ K+ _( M' C; O) _: O. M  N# vprivate void addDetpNameInfo(UserVo userVo) {2 e% R+ y3 N; ~& A- W
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)9 h( U6 F1 R/ a7 o# @' t; @
        .eq(Dept::getDeptId, userVo.getDeptId());
/ u, _4 j+ p, f) ]/ g1 x4 A+ s    Dept dept = deptMapper.selectOne(wrapper);
5 E4 M0 c% j$ h. p    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
% j9 C5 a4 P" U! v3 L9 ?# Y}
( J; P+ J+ e( h, ~* _, N</code></pre>  L  `* x% a: f# n! V" _1 h) a1 s
<h5 id="2理论分析">2、理论分析</h5>8 J/ p! _  r8 v, r7 `# _7 [
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>- L( D. e4 N, i) d
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>2 l; Y/ i0 q# ~  Z
<h4 id="二查询多条记录">(二)查询多条记录</h4># u( j/ ?" e" o# I/ T0 x
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
" v8 t9 r+ G' |7 H<h5 id="1示例代码-1">1、示例代码</h5>
0 V* I9 g4 m: X! B% j7 Z; d<pre><code class="language-java">/**  m6 j4 s+ w& u( _
* 批量查询学生信息(一个学生对应一个部门)
- p" y' d, y$ a% j* B3 q */
2 r* j6 z9 d* W) vpublic List&lt;UserVo&gt; getUserByList() {
3 L0 U! ~/ [4 l    // 先查询用户信息(表现形式为列表)" W4 c8 I8 Z* R
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
+ h7 G- @0 w1 w" I    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());5 ?4 x" D- h: B3 V8 s6 S
    // 此步骤可以有多个
, ^8 m) S' E4 a* ]! S4 y: h- d+ |    addDeptNameInfo(userVos);7 x0 s0 H3 o/ M& S. p
    return userVos;
  z  l, B1 s: }9 F8 \! {. n) b}
- C6 V' E1 [4 y, @/ ^0 l</code></pre>
5 a5 H' I% C9 `6 [<p>附属信息补充</p>
2 p( ~3 M9 _- b4 a<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {
. m, v1 v2 l4 b7 b- y9 j/ ~    // 提取用户userId,方便批量查询
& _, H5 S! O% K' j    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
4 |; J( D# l+ I- X9 b% V4 }    // 根据deptId查询deptName(查询前,先做非空判断)
* w7 U$ _7 `1 Z" K: g& R# v    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));% C4 S- B: G/ e% ~# p. X
    // 构造映射关系,方便匹配deptId与deptName
) K  b% ?7 x8 y% j4 p$ x    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));7 Q2 z' o3 [, V
    // 封装Vo,并添加到集合中(关键内容)! I# s! c/ d1 K- j
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));+ T. V: o; Z# K9 Y, [' ^2 y
}0 e& l9 i5 b3 }  w: I  ~. X
</code></pre>& V. J4 r9 }% b" ?0 O. ~
<h5 id="2理论分析-1">2、理论分析</h5>- ^* l2 |5 }4 O2 g  L0 [
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>" W% L* P+ I; V$ I0 [& n$ t) w2 i: q2 Q
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>( e0 C: F% K2 v9 S1 p, l" h
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
1 o1 f% _! J4 X6 n8 z  P0 @7 p; X<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
/ ?: u/ P, j' [, S3 O<h5 id="1示例代码-2">1、示例代码</h5>2 [! n6 g" F" F" n# K2 q$ O. H
<pre><code class="language-java">/**
5 Y. g; v% x  k- L$ W * 分页查询学生信息(一个学生对应一个部门)
' Y2 J  W5 }9 T& q */% |6 x4 ^# V5 i8 r7 N- n
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
% e9 ]% p) g) ?    // 先查询用户信息- b2 ]4 O* h; Y2 [
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());3 H( {7 R) e( ?
    // 初始化Vo$ F* V" U% ~3 C. c
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
0 D: E8 h. R) o    if (userVoPage.getRecords().size() &gt; 0) {" j& a5 ~4 u  ~. ~: ?  Y+ ]$ l
        addDeptNameInfo(userVoPage);) ]7 [4 S, V$ d  E$ N% K+ \  `9 |% d
    }7 [2 s" _; Q6 C3 n
    return userVoPage;! G, }3 |, K$ H0 E  Z+ s% j
}& `- s* ]& g: G: D9 r
</code></pre>
4 x- J4 W& R- K<p>查询补充信息</p>
  @5 _" p. p) H* t. x<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
5 n3 y1 J: M; ~% ^+ W( z$ F1 }    // 提取用户userId,方便批量查询
1 p9 Y  c" p) y( ]    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
' s$ c2 }! X! e3 T+ w8 p    // 根据deptId查询deptName5 z, [- U5 M0 E, q8 {+ c6 F/ o+ n
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));3 w& B4 d' ~# r9 ~! O  Q
    // 构造映射关系,方便匹配deptId与deptName. m+ ~! z* l/ S  n/ o& m
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));/ B1 F0 |8 z; z2 F1 S3 W# L* }) H
    // 将查询补充的信息添加到Vo中
& ^# F( G$ w- R. k# _  s    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));* B3 l5 ?# ]. i
}
4 E/ ?  M& h6 b" w  `# \. q( U% W/ k</code></pre>2 H9 z* M* C- T, _  V8 z+ L, w* l
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>1 ^- R$ M7 Q  F0 {. `3 o/ N
<h5 id="2理论分析-2">2、理论分析</h5>
/ F# P. t; f* W: D8 S* ]: P' ^( \<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p># z  u, z! e8 w4 O
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
/ |' C" o! p: n$ ~<h3 id="三一对多查询">三、一对多查询</h3>
2 X, ]; I! F7 g" m# `<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>6 l% J: q" o- g* d6 r' v" s
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>; o2 H" c6 g  F  U5 L
<h5 id="1示例代码-3">1、示例代码</h5>; M7 y+ @8 n' o& z6 d6 _
<pre><code class="language-java">/**; S  d4 g( i" @3 H. F
* 查询单个部门(其中一个部门有多个用户)
8 j: F7 i/ G: X */
/ Z$ Q$ N" W% L$ K5 ~7 s& _public DeptVo getOneDept(Integer deptId) {+ M: D+ c: E& e6 M1 ~. @) \
    // 查询部门基础信息* H  o1 m1 J2 ~$ @
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
" h: D  A* u- _2 @  X    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);  B/ n! W/ p3 I* A2 V
    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
* X/ F7 S( G. q3 W5 a& O% [    return deptVo;
6 o% U6 q& L0 W}$ v1 p7 \1 F' h. i
</code></pre>+ ~: S; U/ O: [3 T2 _& G/ Q
<p>补充附加信息</p>
8 Y9 [' U; x- T- B6 u1 `<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {. q/ s1 n2 ]! Z( h9 J# ~
    // 根据部门deptId查询学生列表3 q7 n! e! C& ?: {
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());$ ~) R5 `- r$ `8 B( _* g8 l
    List&lt;User&gt; users = userMapper.selectList(wrapper);: ^; F7 M3 D5 g1 w% i. G4 b3 }+ M
    deptVo.setUsers(users);
1 P3 r2 b) r- j# j* I1 `3 x}6 J7 D6 d" I, R+ ]8 A
</code></pre>, l9 L5 R7 C/ y  p. I: f4 U
<h5 id="2理论分析-3">2、理论分析</h5>+ j( w$ P) i9 o) W+ o5 L( g2 b
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>8 d1 t* `( j6 d' c3 @! Q. S3 i! n
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>  W- S; @9 B" M1 O
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
; h) M8 u+ ?4 D# H<h5 id="1示例代码-4">1、示例代码</h5>
* ^, [" i4 ^6 x0 t2 t<pre><code class="language-java">/**& @. H) Z8 {/ t' m/ ]
* 查询多个部门(其中一个部门有多个用户)
8 t. M- s7 ~; f */! ~2 k! m9 I/ B7 e% s8 s* \
public List&lt;DeptVo&gt; getDeptByList() {
; l$ @7 j5 n# i8 l' k    // 按条件查询部门信息
7 h, P2 J$ G9 f% G5 y$ c    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());$ W4 o9 m& |5 _8 s, h5 J7 V
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
' H& ]4 Q! F# M1 \9 B% w/ K, t    if (deptVos.size() &gt; 0) {
4 ?# W6 }# u# P$ N1 B        addUserInfo(deptVos);
" @3 `( B9 I  H/ E4 \5 L    }) l- a& x7 Z: O( a" R9 c/ r8 f, J
    return deptVos;  n' k" T7 R! r' C
}/ z5 o5 \! p4 c
</code></pre>
8 g+ h+ b1 J/ [<p>补充附加信息</p>
7 T2 A) g5 c! p( Q" v<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {) `5 G9 a8 F& q. ^9 g% }
    // 准备deptId方便批量查询用户信息! ]9 z  {# E! C& r$ c% t5 f
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
" z& Z* K3 b! y& U- Z    // 用批量deptId查询用户信息
, m2 A( Q1 f$ d4 h0 w    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
: L/ B+ t2 S4 w: j4 b% H! T    // 重点:将用户按照deptId分组
6 ^* _9 K7 A, Y    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
0 h8 E6 I" i8 g# d. r. p4 n    // 合并结果,构造Vo,添加集合列表
+ s* i5 M* }, l* t    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));5 i0 s  k7 r4 N9 h9 C4 r# z
}
$ z9 u$ c9 w: f</code></pre>
  X% o. D* ~5 h* ?( p2 D) f* \1 F<h5 id="2理论分析-4">2、理论分析</h5>0 w; `. k" W% c1 ]0 M& {" d
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>) D% H& T! t  j8 R& U. g
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
- P' c5 ]+ A8 _8 J<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
: m6 E% H) O" |2 H0 ^8 k<h5 id="1示例代码-5">1、示例代码</h5>
% Z* M$ \, O6 ~<pre><code class="language-java">/**( @. ^* c) Z( h4 y' a0 y7 ?/ Q
* 分页查询部门信息(其中一个部门有多个用户)
- u# _. i* g( d7 u* U* }7 j( x */
/ ]  A5 j7 @% m' |4 K& gpublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
( i2 x/ G+ L2 o: _2 }    // 按条件查询部门信息
5 s2 a) e# I7 m/ o& b! N# D    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());' F, T8 r% r1 h$ D  e
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);6 @$ C* \9 }; `' Z/ T! b3 Y9 b
    if (deptVoPage.getRecords().size() &gt; 0) {
- g9 h/ S0 L, X7 H9 _1 s: {        addUserInfo(deptVoPage);
! x  ^- Y! n: z- W. d    }
- F4 S) a+ A2 ^# D    return deptVoPage;
1 N+ T1 A0 M8 Z+ _7 R0 G3 x2 V3 b}$ N4 Z8 |1 Y8 }4 g6 k4 s# o
</code></pre>
1 E5 Q: l$ n4 u<p>查询补充信息</p>
) Z0 E4 O+ s" F( k<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {8 T4 K- s$ }! y% i% t6 F: L  ~+ k
    // 准备deptId方便批量查询用户信息
) \' S/ Z- n8 y2 A    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
$ H. j, @7 T- h- N    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);2 J  p1 v0 R+ w% `
    // 用批量deptId查询用户信息
$ |& E$ c* U7 m: z0 o4 G    List&lt;User&gt; users = userMapper.selectList(wrapper);
! y4 a6 z" f& q: s- Y* ]    // 重点:将用户按照deptId分组% C, M* y6 f! {& \9 q
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));/ d! X7 b7 Y! o# S) D/ p0 [( z" e
    // 合并结果,构造Vo,添加集合列表
; O9 D$ W) c: E1 m/ q# D, Q3 o- i    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
5 p: d" M6 ]% v  }' m5 ~/ L) _}
+ d, {( ~, |; R) F. Z2 q" Z</code></pre>' l/ Q3 Q! R- c5 r% D- W" `
<h5 id="2理论分析-5">2、理论分析</h5>
+ Z$ E1 `  ^" R' |6 E" {3 q) [  o<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
# n! k2 ?. T6 z  h* h. T3 a<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
; Z  i  W# f$ G/ \' ]9 G4 u: M<h3 id="四多对多查询">四、多对多查询</h3>
* B. x0 ?6 L; H5 ~# s" Q<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
6 Z1 V9 Q/ h5 d0 U' F7 ~<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p># u" G8 Y, p+ E2 M: E9 L5 j
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>$ t. j+ @" @2 }$ f! ?
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
! y/ D0 O& v8 a, r' d$ A3 Y<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
: R1 U. ?# A% f6 f9 ~- F# I- J<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
# T2 [% |0 D. }: }<h5 id="1示例代码-6">1、示例代码</h5>" A0 G" u5 p  \2 b7 q
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {. `; ^; _9 `: {
    // 通过主键查询学生信息
1 L3 D$ t( X' n% X    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
4 K/ w- l! u2 i! F9 w    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);( z# t: k' j/ Z6 I+ j- H
    // 查询匹配关系2 H3 U% F+ [2 P+ L+ q2 u; ~6 X
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
; Q) z$ d  |. R. b7 y. ?# u    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
1 ^5 |1 F) Y6 \( B$ _) {6 y    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {5 e8 H, j$ b  I  _- H
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
$ D) x8 i( A. Y- R4 t, C% z, i5 L        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
  U4 t1 t8 q0 O/ g5 r$ g        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);. p0 G. k% k  A: e( \
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));. f0 M* c0 \7 h( L+ N5 @) r
        studentVo.setSubList(subBoList);
9 H: J: C7 c. w, d$ ?    }! ?  \7 w( y1 d* Z) R# L+ e$ V. R
    return studentVo;/ v" m0 i: d5 p. I/ Q4 v
}0 X0 j" L% J, ^( m# z) ~, ~
</code></pre>
1 I: N5 |$ _4 _. i- ^7 J<h5 id="2理论分析-6">2、理论分析</h5>
' |0 L/ H7 u, q/ |0 O<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>' G/ t5 T, Z9 O$ ?) P! U# [
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
- k* [& ?& O( b- F, _<h5 id="1示例代码-7">1、示例代码</h5>7 f/ m8 n. {& L8 F4 ?% @
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
7 Y0 ^9 ^( @$ {5 I$ \    // 通过主键查询学生信息
1 M* w* m9 g/ m9 T0 q) L8 [4 g    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);* e( i9 _5 Z& d0 `) p# Y
    // 批量查询学生ID! ]' Q" _  J! ]4 u% H' @; m) z5 f
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());; U0 L0 ?' B; F- J
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);/ l7 ?$ h; M' p
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);0 e* W# M9 p# s6 O6 h
    // 批量查询课程ID# [; c! I. |, q) X
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
9 ~7 ~7 e9 A2 f2 E) g4 G    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
9 j0 |: V. O0 L        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);# P# }* i, n; P  w
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));7 ?" ?$ u% U' |( \% T4 s& w$ H5 L
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
* L7 Z+ p, x2 x0 z7 v0 w1 C4 L        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));  f4 B" Z" ]* w5 ]( X
        for (StudentVo studentVo : studentVoList) {6 E: y" F9 z4 A
            // 获取课程列表3 P) O* l  ^$ S: m
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
$ w2 K* E& J7 n! J, V1 b  s            // 填充分数$ w1 W' `( w" W: d' _- a% y* D
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));5 U, X; K# U4 B7 i
            studentVo.setSubList(list);
& ]2 G) a$ t1 P( b. y        }. I' q8 d: h& U. b# m- I
    }. s5 P7 D( W* g1 T) L
    return studentVoList;# d! H: I+ L3 I: b0 t" n' H
}
2 v& E; Y1 k$ }</code></pre>
/ R- ^/ A7 E# D2 [5 N* J- `: w<h5 id="2理论分析-7">2、理论分析</h5>
/ T+ e7 r. c3 c' }<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p># n+ H" W3 S. n
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
+ v8 X' v  j. N& U5 ~) H) a<h5 id="1示例代码-8">1、示例代码</h5>
+ Y5 c+ F6 i. l& F<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {/ [! B  l! e2 ?- F! r( X
    // 通过主键查询学生信息
$ X- \7 I# k( v) k9 ^. p    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);0 e3 m) O+ A4 c! E
    // 批量查询学生ID+ J( q# [( ]! Z8 v: q, ?2 `" `% z
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());4 m1 e9 ]7 l4 }' p& f" }$ E$ D
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
! h& A+ R6 ]# C" `/ t) l    // 通过学生ID查询课程分数- C3 b, Z  }/ @9 ]# S( j
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);* T1 Z3 i9 X, N, q1 M
    // 批量查询课程ID
7 P& h, M+ u" A6 r; ?' }' [    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());7 Q' G5 x2 t/ q! J
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
& @- i( a( C+ n) p4 s, b( h        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);% `# o+ W! F% G6 ^; s
        // 学生ID查询课程ID组: w7 X- a& K( x- X0 l8 @! ~, ?
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));& c' M+ @# |1 a# v

4 }$ N6 W& f, K' s0 l  C& X8 q& B- ^        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
  t: q0 U6 z2 q# m        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
# Q$ R4 m/ c: c5 x5 C- Q4 j$ E        for (StudentVo studentVo : studentVoPage.getRecords()) {. f8 Z' R" v" N* F# F7 u5 }
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
! k) o9 Y# T4 N7 P/ B- x7 J6 W            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));/ j9 X0 {# {& E* F4 b' h
            studentVo.setSubList(list);' u' h. Q9 c2 A2 c3 g0 y0 C
        }' v, e# N+ k0 b* Q9 q
    }
, a1 Z% A8 s: _( f    return studentVoPage;
# L/ N& H3 y: Y4 _. k; e! F}
" [+ I% L* c0 s</code></pre>9 f7 d4 d% u+ L& Q$ j. q) b
<h5 id="2理论分析-8">2、理论分析</h5>
2 _- A  T& d/ m<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
/ @; J" G: C/ f; S3 J<h3 id="五总结与拓展">五、总结与拓展</h3>
" z$ R' W5 T0 e' ^+ r  }! `<h4 id="一总结">(一)总结</h4>
1 q, ]) H" {# r3 z<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>! i, h3 }) \! N" C& e
<ul>- @! L% h, m( Z: e
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
! U. ]2 Y1 ^$ Q" }8 ]; P5 ]0 |7 j. C<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>% f* ]/ l2 v2 y' u" e
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
( z% L0 |- U4 K5 A3 K. Q3 N4 ^</ul>' S3 g0 r6 E7 e$ z3 f
<h4 id="二拓展">(二)拓展</h4>) U" q8 p" W9 s
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
2 n1 g+ v: f) u" J- d! ~5 D<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>1 K2 V  T! S9 W0 w) L  l8 w3 Q
<ul>$ H/ C, p+ m- R: g2 x" q0 @& [
<li>当数据量较大时,仍然具有稳定的查询效率</li>
1 X8 W7 a! [/ `; {# l6 G. q</ul>
4 ^/ A; s. E# u5 u  K: a2 d- I<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>* @( Q& N" e6 x5 V& Z- q5 c+ Y  o
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>9 y3 a; n2 D, p3 e8 Y) B2 s
<ul>$ v* @6 e7 ], v9 S/ L3 K7 Z/ |
<li>与二级缓存配合使用进一步提高查询效率</li>
( B' J5 L3 @" w- b0 `  c</ul>7 N* e+ i. ?' B/ w. s
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
" x9 o1 O) f4 e5 B4 Q% H<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
: ]2 J/ m7 e' U; v& d8 \0 ]2 _4 p/ Y; t) x6 U; E: O6 ?
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-2-27 07:21 , Processed in 0.064244 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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