飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8030

主题

8118

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-3 10:46 , Processed in 0.067891 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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