飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8061

主题

8149

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

- N$ |7 M/ u; f. i8 Q<h3 id="一序言">一、序言</h3>
( s, ~3 k) [# R* A1 C' p7 s<h4 id="一背景内容">(一)背景内容</h4>8 V; K4 n0 r/ u4 _8 t7 h* @
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
" W4 E! U- e7 i<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>; e6 \( u! }- \8 T5 X
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>, j6 |2 b$ L* b( @! _# E+ S! o/ Y, P
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>4 o5 @( n3 G& c1 [
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
1 V0 b9 h3 l. R+ ]6 D* H& q! `<h4 id="二场景说明">(二)场景说明</h4>8 q# @& |% f; J/ Q: M) R$ V0 d
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
- M8 V) c% K* Z4 a4 G+ A8 ^1 t<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >' a5 Y1 a3 g5 z6 d! {, p" e
<h4 id="三前期准备">(三)前期准备</h4>
6 R+ x/ j- d1 }# p+ j- d<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
+ v9 r; a0 s( R' V, r<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
2 N% A) e0 r3 `/ U<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
$ }0 A$ m  E" [2 X( ?4 A. v+ q<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
& \, f9 d" i6 g2 z8 Y. M0 J- q' E<h3 id="二一对一查询">二、一对一查询</h3>
) R3 C3 ]- u- y, c2 e<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
! ~( H8 T" d6 e& }" }/ L<h4 id="一查询单条记录">(一)查询单条记录</h4>
6 x% O# ~) V' j/ P* _' L) N5 ^$ k<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
& a/ Q' m, `1 x<h5 id="1示例代码">1、示例代码</h5>
, z. C+ {5 E) U<pre><code class="language-java">/**! G( R, b2 Z' X8 S
* 查询单个学生信息(一个学生对应一个部门)
" Y; W6 q. Y6 S6 @) u! E */3 O0 {! }) }9 ~0 N+ R
public UserVo getOneUser(Integer userId) {; z4 h' h: s; L6 m
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)" l# i. @6 {+ R. c$ S
        .eq(User::getUserId, userId);
9 ^7 |2 U5 G+ G; ]  e4 q    // 先查询用户信息0 `: ?7 c" v, A
    User user = userMapper.selectOne(wrapper);
4 C0 I$ }0 C2 c& Q    // 转化为Vo! Z/ q- e7 [  g- g/ z4 v4 {# D
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
4 T- |& [$ F0 x1 u    // 从其它表查询信息再封装到Vo' n. V, L; i, i, ~
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);, j8 {* N: Q& Y1 }
    return userVo;, U/ G0 b# i# j0 G9 `+ _  p
}6 `( P5 A  u2 t0 w0 o& ^) w
</code></pre>
& h+ a7 n! z+ h<p>附属表信息补充</p>
( M4 l  @+ F& _# G- S<pre><code class="language-java">/**- t4 b4 ~1 S* k' y9 P
* 补充部门名称信息
! \* S- D: P* ?# E5 x# d */7 h2 H4 |3 D# L& c, Y; x0 Z
private void addDetpNameInfo(UserVo userVo) {* D* c' ^* h" n- s
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)7 l; u/ N3 t2 {$ L% n
        .eq(Dept::getDeptId, userVo.getDeptId());- P. Q5 j3 I/ y$ \) ?3 ~
    Dept dept = deptMapper.selectOne(wrapper);
6 Z" v  L6 {" B* u; S9 A7 n    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
2 ^5 X! y! z* u1 p3 s+ p}0 M/ Z$ `  q& j) _- q0 H
</code></pre>
& A7 j0 q0 y) X+ E2 b, i2 C8 H0 c<h5 id="2理论分析">2、理论分析</h5>
* X4 R) q9 |8 z% O: @  X<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
) S7 m  F1 N2 e; w<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>  h  n1 U) e2 @9 K/ H  }
<h4 id="二查询多条记录">(二)查询多条记录</h4>. p- I. _. @6 p
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>/ [$ Z/ ]# X2 Q$ ~2 U+ N! d0 F
<h5 id="1示例代码-1">1、示例代码</h5>
% a! l1 T9 B( z6 E  c$ @<pre><code class="language-java">/**
% H9 `% P7 a6 H$ Y  \5 I+ X+ t/ `. j * 批量查询学生信息(一个学生对应一个部门)4 v! M/ P4 C9 L! z/ G! T# C
*/
+ h& M' o; r: V# _  T9 V4 Mpublic List&lt;UserVo&gt; getUserByList() {
" d0 R, c* B2 n    // 先查询用户信息(表现形式为列表)
6 p; C5 g& j' `8 k    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());& r7 T6 l+ c( b. z) b+ z8 D2 m
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());5 @! o; Z- m) h: V  F/ i3 ~7 B/ [
    // 此步骤可以有多个5 H, _4 v; B2 p* `2 N
    addDeptNameInfo(userVos);
; _. B: @3 {8 @, S" M4 o    return userVos;
  A8 j3 Y! p( H4 @}' N: _8 l! E* x/ X7 A
</code></pre>$ m5 J- X6 t  M) z
<p>附属信息补充</p>% w" x7 x- Q  p, s, H. O! L
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {, G, S1 \$ {% p6 @$ w- L
    // 提取用户userId,方便批量查询
9 J4 }6 R1 C6 r3 r8 A    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
( o, |" h# J# o" k) j! j* b; I    // 根据deptId查询deptName(查询前,先做非空判断)
4 y; m% \& D+ i5 `  Z7 y. M2 E    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));% e" i7 n# C' ~8 o* t
    // 构造映射关系,方便匹配deptId与deptName' Q. i6 v7 ?2 b! R3 V  |" y
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
- R. ^: T* y% E1 G& N    // 封装Vo,并添加到集合中(关键内容)
  e+ [+ v7 [- ]$ k, m    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));; Y1 X6 \' s/ H8 A2 X2 n1 Q3 r# r
}
9 c6 W. u& i& x4 Z( p' m% J( N8 [</code></pre>( a9 F* N& S  |3 t5 {3 j3 p6 q$ e
<h5 id="2理论分析-1">2、理论分析</h5>
) O) c8 t3 _. S* E& _' ^- x<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
3 T& T. j9 _' J<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
- T3 x/ Y  L" t" C1 L3 ~! P# x8 y, N) A<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>% o5 I! A& D* K+ R1 R; }
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>7 b3 h; v5 r; ^+ O
<h5 id="1示例代码-2">1、示例代码</h5>
% Z: b) a6 N) v7 h6 ?( v& C& @<pre><code class="language-java">/**
4 l- s5 J+ {9 d3 f8 K * 分页查询学生信息(一个学生对应一个部门)
, `4 @( S  d9 Q# M& E) q. z */7 J. l& O/ ?2 w$ ~1 j, u. }; _( I
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
. w5 i) E3 o- D0 a; C    // 先查询用户信息
, o, d' L6 @" q    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
. b5 `; Q$ X& E' Y, ]9 L    // 初始化Vo4 \" ~# f' |" u1 q! F3 ^
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
8 `& Q; ?; N3 `& h& w    if (userVoPage.getRecords().size() &gt; 0) {7 i; G  g. {, j. `
        addDeptNameInfo(userVoPage);3 @: f3 q5 c: g) q5 Q
    }+ n. Q& M$ q1 _: Y
    return userVoPage;$ x: |, [0 @  x( D9 L( p
}
" U: l# U; T* Z4 m* P9 s</code></pre>
8 b! g: |$ G- v9 a9 g7 p) R<p>查询补充信息</p>* {! E" }/ ~: }, G* X' R: K
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {! G) C* S+ H) {9 f: T/ p6 ~+ }" _/ d
    // 提取用户userId,方便批量查询3 ]' B, R: {" i9 y0 g; J, w7 x- }
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
* q! G1 m0 R8 y  S    // 根据deptId查询deptName
0 W$ o& o( F/ A1 s, `    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));+ v8 b/ Y" p4 b3 x$ a4 }: a
    // 构造映射关系,方便匹配deptId与deptName6 S9 l5 v# k  E3 ~( z/ N8 a( |
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));$ n' x& P  L- L# m% g
    // 将查询补充的信息添加到Vo中- Z  w7 s* c/ Z' g( ~7 A2 K
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
4 g. ^! D/ u: F. b}3 E. a1 U2 q0 ~+ v  D% F4 [+ X
</code></pre>
! V& Y9 Y, x; r* S# W8 q<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
1 Q- n1 M& ]) i) W  g% t<h5 id="2理论分析-2">2、理论分析</h5>5 L  R: K: L8 T
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
- A' r3 \2 {  Z+ E; U* N9 K. S<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
. b3 ^* }8 Z3 ^6 a! q  U<h3 id="三一对多查询">三、一对多查询</h3>0 L9 ?4 t3 g; `) k
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>6 Y7 y8 K, l: q& D6 v* l
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
& F  b. a! B" q* x8 ?+ W<h5 id="1示例代码-3">1、示例代码</h5>; Z$ \# o4 K- B3 b/ {/ D) |% P1 g7 `
<pre><code class="language-java">/*** ?$ ]1 W/ A4 ~
* 查询单个部门(其中一个部门有多个用户)
% }8 u" j: V- [1 { */
. ~! G: _6 m) E2 B3 D) P* e5 bpublic DeptVo getOneDept(Integer deptId) {
" _4 B- J9 h. w% m$ d- o) _5 I- V    // 查询部门基础信息
; h  ~$ S5 |5 I2 r' n. p    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);$ _2 w* R) g5 v( e* {
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
/ o& |. y2 T* H5 W9 @; d    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
. P' l% g$ k3 J' t. C    return deptVo;3 E$ |9 m0 Q. H& s  _6 e: }( ~
}+ y, u8 p" Z" ^6 {
</code></pre>
. ?8 D/ c( Y& ~  Q" }8 E<p>补充附加信息</p>
; g  B1 B: j/ U$ l9 I<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
  J! h- D0 J2 v- Y! b8 S$ H    // 根据部门deptId查询学生列表1 R! z% [$ ^2 z" b
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());0 Q9 f! k3 y; {( {
    List&lt;User&gt; users = userMapper.selectList(wrapper);
, f9 A/ Y* N- |' a2 Z    deptVo.setUsers(users);" ~# }9 d  V/ b( h" T7 o
}
& b/ M! x$ z# I, V6 d) ]1 Y</code></pre>
% P1 ?* \" b8 N. u<h5 id="2理论分析-3">2、理论分析</h5>& }5 h3 J, O0 g! o# t* C% ^1 @
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>1 l1 ]+ a8 V1 d2 W4 S' a
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
; x  p' g7 m4 r3 A% R: _) X8 m<h4 id="二查询多条记录-1">(二)查询多条记录</h4>1 C7 e, c4 j8 m3 u7 f, [6 r2 {% B
<h5 id="1示例代码-4">1、示例代码</h5>
+ [% [/ P. U/ T$ [7 B& ]<pre><code class="language-java">/**
( [9 \% U! a2 }- L$ Z! x4 z * 查询多个部门(其中一个部门有多个用户)
1 x! B. j4 L' ~  `8 g# ?6 }4 A */
6 E+ a3 b5 L0 }" q* r8 Lpublic List&lt;DeptVo&gt; getDeptByList() {
7 @5 k+ j8 g  h    // 按条件查询部门信息
' |0 R0 r% J1 W( c1 q* S    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());" |! g* U+ U* ^. y
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());9 q+ a/ r& K7 F3 H: J" o
    if (deptVos.size() &gt; 0) {' x* I  M( C+ B& s
        addUserInfo(deptVos);; R) s$ I" S0 E8 Q$ x5 J
    }$ H0 R& b6 B  x9 N
    return deptVos;
- V, L* V9 c/ k. l}" ]% g. H5 n8 l3 s9 {4 Z+ Y
</code></pre>0 y* h( f; }1 U4 v/ i/ E! S$ k2 p9 q/ A
<p>补充附加信息</p>/ G: o, `, V0 L. N7 v; N
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {" W  y2 t) q8 k8 E1 p% p1 e
    // 准备deptId方便批量查询用户信息1 L  [" W+ \' f5 X- S
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
  h2 K0 v% D" i) L; e8 N    // 用批量deptId查询用户信息- Q( y; z/ M' H- ]% a
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
6 B5 j" y8 s: L3 w( K$ l    // 重点:将用户按照deptId分组$ s4 l# N5 _: w; @; P/ ~
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));% N; ^# I! A/ _  L- `  d7 }  m( e
    // 合并结果,构造Vo,添加集合列表/ C- b" M/ b' m/ U* }
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
/ x( |6 A. X% K& ~}  c' {. P; g$ X0 T4 F
</code></pre>
! l. l" a2 o$ t4 D) h# U<h5 id="2理论分析-4">2、理论分析</h5>
2 F( s6 X+ ^8 T# ~* Z<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
# {+ {  j" g: G3 d0 K* L<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>7 d. @" D/ w4 `/ T" c# G
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
/ J) B- V3 h3 j5 T7 x4 M8 f6 S<h5 id="1示例代码-5">1、示例代码</h5>3 |# S  _( \+ e2 w7 y
<pre><code class="language-java">/**9 w+ ~+ h% `1 @$ C. P, V5 i
* 分页查询部门信息(其中一个部门有多个用户)2 C6 \- O' D+ [8 g0 e
*/
  q0 B6 ~$ p' K" a6 Tpublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
* K  z8 ]* e! b# ~6 R    // 按条件查询部门信息, s4 B4 p3 |! O7 p
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
; w  K) q% }) @9 t" V; ^8 B5 U    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);+ [  t+ l3 R% T+ Q6 C
    if (deptVoPage.getRecords().size() &gt; 0) {
% }7 F8 X& Q$ W5 j( b; V) n% Z& s        addUserInfo(deptVoPage);
' u: }/ s3 |, C3 I8 d* D    }
+ S& |$ ?1 Q4 c) R    return deptVoPage;8 E# H# M5 g: K6 E- a
}3 o! r& M$ ?1 @/ r
</code></pre>
5 X, X" I1 j5 p; d6 O: C' a<p>查询补充信息</p>9 Q5 f& h! k# Q6 z9 `
<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
( ]9 _" {' e+ G8 N: k% C    // 准备deptId方便批量查询用户信息: S/ O6 T0 C% |; m
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
1 r+ c2 N- a7 I- X$ ^    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);0 t: J# e8 F" Y4 s2 o; ^
    // 用批量deptId查询用户信息
* I0 Z& `% c! @% h    List&lt;User&gt; users = userMapper.selectList(wrapper);
7 o" d, H3 |3 W9 {$ }; d    // 重点:将用户按照deptId分组
" p! u) ?6 a# u4 f, p    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));2 y" f" Z! G0 G, |
    // 合并结果,构造Vo,添加集合列表) d/ O/ a1 j7 B2 Q  R1 y) K
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));% [$ l& J# l5 j2 r  S) {2 e
}9 N9 q9 q6 M) b
</code></pre>
2 X* `( C- z. y4 L& a: _- h<h5 id="2理论分析-5">2、理论分析</h5>
9 [; V. ^2 _9 v) W; [7 v5 C<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
5 O6 `" d* S6 A7 w<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>% ?  G% R7 [2 W7 ~- u" e
<h3 id="四多对多查询">四、多对多查询</h3>. D+ u8 w9 q. s* E
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
3 D1 g: U1 D. ]% D5 i<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
8 p* f' o) ~! o1 ?: N( T- }<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
6 m# Y) R! S3 N3 b' G<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
1 Z# Q: d) x( E6 a% L1 l& m<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
& w% i5 U  z; {: O6 J<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>4 f# e, L% S" Q  K/ u
<h5 id="1示例代码-6">1、示例代码</h5>: X. K! i0 y3 v/ s
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
" k" R$ e* K( ^1 r- D; f; I* q) J    // 通过主键查询学生信息
6 M3 \$ w, f4 o5 M) M5 O    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
; M$ V( J4 v' ^0 Y" l  @8 `1 T: v% O5 }    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);0 p3 K: _, @! r6 r) S! M* f4 ~
    // 查询匹配关系( y- ?. A% L$ X
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
  Z$ R$ `  U" k7 k) ~/ _    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
4 b( W4 x  X; @4 F9 f2 s9 p    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {4 m7 ]8 ^! b4 [8 {: _
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));' v8 ^# D) d* N
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
0 Y' U0 N" L4 o% d5 _# r# ?) L        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
# U% I2 R  ]# g/ @        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));" p( `  }$ k( e
        studentVo.setSubList(subBoList);1 w. C0 \% ]3 U( A; k% ]
    }
& {( t* ~% V9 {7 `; E" R% N$ t    return studentVo;+ D% w- M. }1 X* Q
}
& J/ {8 w% o. y</code></pre>5 c7 T# F. w& h. H
<h5 id="2理论分析-6">2、理论分析</h5>
" J, V4 U2 M5 s1 j( B<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
! ^" }- j9 c- e5 o; }( g<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
- F9 m) {  l3 M<h5 id="1示例代码-7">1、示例代码</h5>
7 i6 A) w$ r- x4 x* b<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {4 A" r7 s, W5 Q* J9 h
    // 通过主键查询学生信息
) s: W" T7 S. X# L) I2 y& ?- }    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);6 L2 W/ I/ I1 M# W$ {4 e+ g; F& b
    // 批量查询学生ID: \  s; x; M" N% N- R
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
% S# B7 Y6 A; D- x" I2 b    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
5 g; [8 _, s9 K5 R9 m    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);" y6 V' E2 S, o) p3 |7 N
    // 批量查询课程ID
+ {$ r, [9 i2 a    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());7 H/ C. W4 f% k3 u* x: x. G
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {7 A  p# n" G6 w8 \
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
5 d0 V! r' u1 o5 F5 A  ]9 W# r        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
0 \) s5 `# t! b" n. u  j        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);% [9 l( {' g/ @4 W
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
9 N, k0 w: T, p+ x        for (StudentVo studentVo : studentVoList) {# f3 ^' s0 b$ _2 T/ _0 h3 J
            // 获取课程列表
  z+ b7 l  x2 k$ Q/ P2 w8 q            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
! ]0 t# [, X; m) H$ n( T5 N! i+ S$ k            // 填充分数- }5 u& _4 ~% A- i: I/ e, _
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));3 w; D* A4 s+ `' D+ Z* N
            studentVo.setSubList(list);4 Q6 L# {" e, }% D8 I2 i$ C* z6 H
        }1 j8 u% W( U( N8 @3 O
    }
% V+ s0 e  @6 ~% o9 _& J2 B! V9 J  u    return studentVoList;* [2 a. o) v1 ~7 z7 b
}
" }/ t8 x) Q4 _" a  L! u& ]</code></pre>
% c( z! y# H! z; ]0 i<h5 id="2理论分析-7">2、理论分析</h5>8 u0 C0 z+ E1 S9 [  h0 v# J
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
' R' r' s" g- b" Z6 Z, m: L/ s<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>+ j# c5 V, M& T5 q
<h5 id="1示例代码-8">1、示例代码</h5>
# u& j8 J( r8 z2 H7 O, j<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
5 A* J5 a* Y+ Q9 Z    // 通过主键查询学生信息
" s8 }3 ^5 T# o. y, Q4 B! y    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
$ k& H' e* g7 \* A; B    // 批量查询学生ID5 Z+ n: c4 h) L2 z2 h4 J
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
& O5 [% C* Q: W, O& {    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);. j+ M" b4 r4 Z& N, E) D; O
    // 通过学生ID查询课程分数4 u, V$ x7 d, _6 G7 q6 v3 n
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);7 X! @8 L1 T: t. u7 g# O
    // 批量查询课程ID9 i- ?+ R) S) ]3 i# H! ~
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
6 ]2 T5 {9 Q0 E* P    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
9 F4 T: E" b3 w2 F9 v        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
( G% u) S' D4 {0 w7 s& m4 c        // 学生ID查询课程ID组
0 l0 N( m- F1 a& E+ X$ H* N        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));  w- v& d0 U" _1 i0 [" f0 |
8 C% g( A& c* g7 d) d! m0 [+ J
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
  p! y4 R+ }: X! _( L7 J' D2 I        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
( x  i. u) V( \# T# Y$ x1 e4 z8 U        for (StudentVo studentVo : studentVoPage.getRecords()) {  S/ ~/ L$ q+ U; W
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
) e# ^2 U  Y7 t  P            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));: {7 M& e+ \4 R" v2 L+ n; ]* b
            studentVo.setSubList(list);
4 z% L+ X: F7 [! W- X- {        }- k$ w7 R9 ?; w# }% }8 i6 m  c1 ~
    }
" U6 |0 p) d0 H: F4 p    return studentVoPage;1 o. N. ^7 n/ z1 {( b
}
# B! w: z! ^" ^- M% t</code></pre>
4 d# E' z+ O9 B<h5 id="2理论分析-8">2、理论分析</h5>8 L2 K9 q1 ?, v
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>4 L' b1 F2 y1 D4 |; d: ^7 y; D
<h3 id="五总结与拓展">五、总结与拓展</h3>
8 M- [3 t5 i: f- Q<h4 id="一总结">(一)总结</h4>
" R5 D* E, V) _8 p<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>% e( |6 x' m, A+ x
<ul>3 D" @- c" u& [
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
' p+ K0 k# v0 ?* S<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
8 {& ?9 B* e7 t" s<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
- R* h+ m6 ^" h' l% M( p9 C( x" \& M</ul>
$ ?6 b) u" ?$ S8 N- h% g<h4 id="二拓展">(二)拓展</h4>
6 r) |# t* r2 m, I2 G! I<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
( D9 `/ h6 k9 F  x<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>$ D2 h" ~& |; a2 X) m4 h$ K( O
<ul>
# `; J+ c" |8 i8 W' l<li>当数据量较大时,仍然具有稳定的查询效率</li>! U3 I- ?; ?4 [: M
</ul>2 A2 M( A# o3 }3 w8 w
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
; n1 P7 z( {8 ]" A<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>* K# J: `" O2 v# h% D
<ul>4 a' H' P* c1 M9 V
<li>与二级缓存配合使用进一步提高查询效率</li>8 |# `' }3 [( |  P/ {& e6 p
</ul>
/ {2 K7 M0 W: k) ~- p1 I- `6 [( z, F# t# R<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>( X  G! `/ J$ |' w4 d$ c6 f: X+ p
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>0 i9 `! r5 F1 o/ l  m: c* H. {
2 r! x; E$ P$ I2 t3 \$ s* a2 X
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-15 12:58 , Processed in 0.326589 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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