飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8240

主题

8328

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

6 E, J) L  U$ R/ s: `
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-1-12 15:13 , Processed in 0.067517 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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