飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8242

主题

8330

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
27056
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
2 P2 l9 o3 c. O
<h3 id="一序言">一、序言</h3>6 |+ P& O1 L1 G5 ^( R$ K
<h4 id="一背景内容">(一)背景内容</h4>6 ~# E0 W) ^) c1 v0 n6 ^' Z
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>2 f$ f5 o& W: y$ X9 w9 Y1 ^
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>( k. g. _. j5 e. u% o' c/ R
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
/ |' Y4 }1 c! M2 R, q$ `. \<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>( l1 t8 r, I3 [" ?
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
3 M8 Y/ ]; y3 I6 s1 O8 g% ?<h4 id="二场景说明">(二)场景说明</h4>' f+ J, U1 n9 ?* H# ~
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>) D0 A  x& K! ?" o
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >9 W$ p$ h, F" i( H  N
<h4 id="三前期准备">(三)前期准备</h4>
" Q+ o/ k1 |) W; }$ _<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>1 }: l2 Q% r- G8 X  I+ u5 E
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
9 B% d9 G/ N8 D6 i. C$ e( F<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
  ?4 |! g" V; _<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
  h6 ^3 u- p* }! K" s<h3 id="二一对一查询">二、一对一查询</h3>/ Q# T: c4 C( h2 c1 v6 E4 ]
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>8 ]9 }: q$ e% a5 d0 z* e( B, g! R
<h4 id="一查询单条记录">(一)查询单条记录</h4>
( u6 h- y& k3 v' k7 [/ L<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>! ]3 ]# h% q: Z5 b7 ^4 z
<h5 id="1示例代码">1、示例代码</h5>7 ?! j1 U0 a! t7 ~9 p6 d
<pre><code class="language-java">/**4 F. |* z+ k7 M: _8 p! @
* 查询单个学生信息(一个学生对应一个部门)
& [* B. Q8 W  l9 d8 m& i" s */
: v0 y' b2 k+ q4 rpublic UserVo getOneUser(Integer userId) {
; g0 Y9 t, F+ C    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
5 K0 o. ~' N7 j8 m$ m! U        .eq(User::getUserId, userId);
2 M. B# H$ _9 A    // 先查询用户信息
( |$ s4 P/ N5 ?- `+ P    User user = userMapper.selectOne(wrapper);, c* r; b' \) `7 P' K- [
    // 转化为Vo
3 D3 N! J8 j. s6 b3 ]! M+ Q    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
) ~2 P, q) @+ Z6 Q! ^1 }    // 从其它表查询信息再封装到Vo# M6 s( ?0 a2 k% k6 ?- ]
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);; g8 r" [. x) n; X3 O
    return userVo;
' X% `+ l6 n3 Y* p}; {/ |1 }1 [' t( F) k# S$ C
</code></pre>
: K( k3 x  d* S( q8 ^2 P! z<p>附属表信息补充</p>
# T$ m* A3 w# L<pre><code class="language-java">/**
6 U3 u5 P6 k2 D1 K * 补充部门名称信息
" i6 L8 H  Y. Q! {; i3 F  K2 `1 @ */- T2 _& j: G3 V9 s6 ~
private void addDetpNameInfo(UserVo userVo) {! i6 j) e$ O: [- ~9 Z- t
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
$ c- a" U( t+ B, v, a  p        .eq(Dept::getDeptId, userVo.getDeptId());
' G1 r5 b6 ~4 M, r6 Y+ x5 k  K8 Q    Dept dept = deptMapper.selectOne(wrapper);
. W$ S* k: \2 L8 C, h% o# A. a# }    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));: D( h! z: A2 W0 p
}( ^! C2 u/ p4 ]9 A" X1 I: f* D
</code></pre>
* N: e" o/ G# V. \3 x% G  q<h5 id="2理论分析">2、理论分析</h5>/ Y/ ~1 z3 v: ?/ n% W
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
- L! v5 I% f% u! n3 G<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
# ^8 l; n7 r* J& U3 m" z4 V" l<h4 id="二查询多条记录">(二)查询多条记录</h4>
5 Q- s0 v0 y1 l  A+ @6 b0 t<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>6 [1 U+ B. J" i9 ], H
<h5 id="1示例代码-1">1、示例代码</h5>
) e$ S/ j' Q$ H6 G) R8 M<pre><code class="language-java">/**. F! A- N, d8 O: R8 T% i# I
* 批量查询学生信息(一个学生对应一个部门)% {, v8 u' {( g) _7 U5 k
*/1 w2 B$ z5 H6 H4 c& K6 O
public List&lt;UserVo&gt; getUserByList() {
6 T( a9 F2 T) s6 j6 Z    // 先查询用户信息(表现形式为列表)4 H; @6 {: y& X8 d0 g) s
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
( b: @0 v" N3 }2 u2 f& @# e    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());" B0 }9 A# J; L2 d
    // 此步骤可以有多个+ E$ V2 x6 P/ D, B
    addDeptNameInfo(userVos);
! H- v; m; C( S; n5 L+ ~  X    return userVos;
# l1 X0 l$ z/ x2 N8 r}4 m0 S/ j* s" M0 y" s# z* l
</code></pre>
  w/ b' _4 T+ P& Y7 m  K: \+ L! `<p>附属信息补充</p>
2 Y( s) \) _4 F% ]<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {; p# R+ N; Z8 C8 q; T1 p2 ?
    // 提取用户userId,方便批量查询5 l# Y* S' p0 S9 q2 q0 s$ i& M7 |
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
2 h* Q( l) N* V5 c" `1 o    // 根据deptId查询deptName(查询前,先做非空判断)% K" ]* O7 Z, S
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
3 }: Y5 M9 `# U4 A. S7 H    // 构造映射关系,方便匹配deptId与deptName% g0 z# z- c# E4 b
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));' [& n3 ?: e4 h7 H% X8 e
    // 封装Vo,并添加到集合中(关键内容)
9 H' u6 [, {6 A4 d- ?/ {' j* F% N    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));- f5 B' n: ?( Z. B! H+ ^
}# n$ u, t# p1 X( P$ ^7 }5 o
</code></pre>1 B& I1 a+ i* H1 P1 U- D: c2 x
<h5 id="2理论分析-1">2、理论分析</h5>
( `$ a. `$ U& X0 T7 O<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>  e- F& N- Q/ t  _
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>! T6 `9 g6 [1 x% ~' h( P) c
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>) {  B" F; r! u7 K4 _, h
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>7 C. U4 G, t1 V. Y# b  \
<h5 id="1示例代码-2">1、示例代码</h5>  \" q: r9 n* G' e
<pre><code class="language-java">/**
+ v# y8 D7 f. x1 d' ]2 ^) w * 分页查询学生信息(一个学生对应一个部门)+ @1 V, }: h2 E9 D6 y8 T
*/% x/ [: W- J8 x$ P; v, b5 e1 q/ }
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {! C5 ?4 L9 u8 `; o6 S
    // 先查询用户信息
- a5 P! w* J) y, @0 S  I; u8 _8 I    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());0 E7 s+ k; z: }
    // 初始化Vo7 C+ ^( \: I9 i# ^
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);5 ~1 j. a* {8 X5 D2 m9 ?4 ]9 b( N
    if (userVoPage.getRecords().size() &gt; 0) {
* E3 B" L$ {; d9 @( V2 k        addDeptNameInfo(userVoPage);
: ?/ s+ o( x4 U  q( p, \    }
4 o+ n% n# I& U+ [# E    return userVoPage;
0 T) e) {7 ^, v5 r  O' U) D" W}: @; W8 G( z3 {+ S( r1 ]
</code></pre>: B+ g+ `2 c: f- g: F
<p>查询补充信息</p>; P* i4 G% U2 \% z3 p7 h
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
8 T4 v2 U  |* W. d. k    // 提取用户userId,方便批量查询# z# W: ]3 b) U8 K3 Q& G6 q. B- R
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());. @5 l+ c( T& u& B6 E
    // 根据deptId查询deptName
4 p5 }6 [. D( k& r    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
; R/ {  K5 z: Q) x    // 构造映射关系,方便匹配deptId与deptName
4 z# G$ ?6 s# f2 {6 U    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));' }  v! D4 B$ Z
    // 将查询补充的信息添加到Vo中( L" P; A" U7 @+ U
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
6 Q. g. k2 {, I! [* a6 J" R& o}
6 x! }& J: ^$ @& ^, Q* H- c* B</code></pre>4 `& e2 C+ z; E" b' F
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
, ~/ X/ b1 B/ I8 f% v" H<h5 id="2理论分析-2">2、理论分析</h5>3 X$ t) h8 Y) B$ ]" h6 s! ~
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
7 F8 ?$ ~# ?6 u( m8 y1 o<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
2 I2 O3 a; [; X+ M<h3 id="三一对多查询">三、一对多查询</h3>  @2 }$ o" `9 E$ g& ^
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>  V  |+ D1 B$ u; V0 I8 \
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
7 G: ]3 e" ]. P2 g  f<h5 id="1示例代码-3">1、示例代码</h5>
3 v3 A2 G" X: Y9 B5 h1 q! l<pre><code class="language-java">/**
( L3 x" k1 j2 c" h0 A9 G) o& ^: {/ G * 查询单个部门(其中一个部门有多个用户)
5 V* T# f. w. s9 k2 C6 @' w */) s. a8 |* w9 C) W
public DeptVo getOneDept(Integer deptId) {
* h7 ]# @4 @, d5 j& k* o3 ?& ]    // 查询部门基础信息  \6 j' {3 J# H6 g  C/ ~, g+ e
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);* F. N% \& p* \) B1 z
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
1 F" @  _6 E) x( T8 \1 z    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);/ ^2 }2 S" o2 Z. @7 r% H7 B* f
    return deptVo;+ i5 O: N$ w3 l& [- Q# b4 y
}4 a. r& E; k# R9 q- y  [! b
</code></pre>* `/ m  S+ d2 b' v1 `
<p>补充附加信息</p>' D& P9 b" n1 r0 j2 n4 f, V* R
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {6 x4 _5 [, y2 ~& @) K
    // 根据部门deptId查询学生列表& ^5 j# [1 c  I. _* u" B  {2 D
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
6 I- A, g5 d! B% M3 j; |9 u  {    List&lt;User&gt; users = userMapper.selectList(wrapper);
' p+ B5 a  y; c# v* L9 ^' r    deptVo.setUsers(users);: U& _7 A! p6 z6 R: ^' `
}
) d, E+ L  ~( a" G1 p</code></pre>
7 f+ }& p5 Y; x. k! C<h5 id="2理论分析-3">2、理论分析</h5># i6 j+ x# S, @+ T
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
9 {, h1 F; y: O6 _& v9 G<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
8 Y/ y: K2 w% a2 M9 m<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
+ p- g) G: D" f, `  o  \" e<h5 id="1示例代码-4">1、示例代码</h5>! C; L* S2 d0 M0 r4 P" o
<pre><code class="language-java">/**
. @# Q- v6 }! l- d: H * 查询多个部门(其中一个部门有多个用户)
# V$ f2 \2 w4 a */5 y9 a6 O( w; x; c4 i0 B
public List&lt;DeptVo&gt; getDeptByList() {
% p- f5 b% N; I; w8 D    // 按条件查询部门信息2 l( }" A+ g9 P! M$ Y8 A
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());$ Z2 v1 q* |" I6 {1 A  h) q: a2 ~8 K
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
6 C% F3 _9 }2 ^3 J% `6 k    if (deptVos.size() &gt; 0) {- f4 f5 x2 p$ I& }# Z4 |
        addUserInfo(deptVos);
6 w" _; R% U5 j6 H5 k2 ], [    }
  Z* A2 p4 {9 Y1 ?" B2 `    return deptVos;
  t" T4 l7 ^/ L1 e3 V1 |9 Q}
0 H! S, y2 B0 _. k+ s0 p- v7 C4 ^/ z</code></pre>7 ~& v8 z& D# S
<p>补充附加信息</p>; n7 E6 N% W2 _* d
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {* g( X3 S- u9 _2 s, l
    // 准备deptId方便批量查询用户信息
6 Y  ]3 F2 o9 A, j$ l+ }    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());" C5 P! ]" n* I" i4 R
    // 用批量deptId查询用户信息
& g  }; }$ N1 Q; W4 Z: Z    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));# ]( v' x; s* l% u/ ]* _' b6 I
    // 重点:将用户按照deptId分组
1 K0 H( k9 c) u& n( X7 k# j    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));) _# H; |; Q2 k% t: w- E
    // 合并结果,构造Vo,添加集合列表
9 a( J5 _: U" L1 [4 M) D( L8 v4 G- C    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));( I+ s  Q$ L/ m1 x9 R4 W6 N) O7 r
}
  U$ O7 P9 T$ E) g( A! M</code></pre>
" H. u2 h. s) |<h5 id="2理论分析-4">2、理论分析</h5>: ~$ B% [3 B0 T* Y9 b
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
3 M- r& b$ i. E  R( g8 C<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>/ |7 J8 x! m4 |0 [6 d9 b
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>4 p; m! F* _2 n- C# Z
<h5 id="1示例代码-5">1、示例代码</h5>6 h' r: ^# G( B) ^3 F/ i
<pre><code class="language-java">/**
4 s. B# y! ?: o' i * 分页查询部门信息(其中一个部门有多个用户)+ Q# Z% @% q/ r
*/
+ e0 Z! h# I* l* ?% F6 o/ qpublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
( u% N+ x+ B) P6 a$ Q2 J6 ?' J    // 按条件查询部门信息5 e/ y6 j+ R0 A& Y
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());; w( l# i4 t& D& K/ p3 Q/ H: D
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
) o/ O% Y$ X' w$ a! a    if (deptVoPage.getRecords().size() &gt; 0) {/ W+ d9 ~! X) C/ W4 N4 s+ U
        addUserInfo(deptVoPage);$ j& J+ W7 H- E6 J
    }
3 j* ]2 B. f& O    return deptVoPage;
4 h+ h5 }3 B( w6 _2 ]}8 E) ?+ J6 v; w0 ?9 _4 J$ D, k& e+ z, h
</code></pre>. x! v- }" k7 y5 l; H9 ~5 L
<p>查询补充信息</p>
& }$ B7 x5 w1 e6 |  S<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {: Z( F! J/ M7 X9 K8 ~; l4 O3 p
    // 准备deptId方便批量查询用户信息
- e9 w! _" v% j5 L2 U# y7 P0 c    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());* C3 c" O4 k8 y1 s, s3 Y, _8 V
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);) U& m5 R& R* f
    // 用批量deptId查询用户信息
( d6 ^4 l: w7 S' m    List&lt;User&gt; users = userMapper.selectList(wrapper);
: O& U7 V: ^2 X( d# A; ^( i3 k! t    // 重点:将用户按照deptId分组0 Z6 ^0 m, N- G
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));- i9 t, r+ U; F3 M  z: }
    // 合并结果,构造Vo,添加集合列表, a$ L5 _0 w# D
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));" V, g: R  J& ]: v: z1 Y
}3 g3 Z3 B! f, {: G4 m2 T6 v
</code></pre>& j' I, d: `7 u/ r4 g! b, u- @$ @
<h5 id="2理论分析-5">2、理论分析</h5>
0 k& {% h- M0 M5 D* I<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>, R* O" [+ }% R
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
5 u5 f5 f6 ]7 T. _9 R, q  ^4 v- l: I<h3 id="四多对多查询">四、多对多查询</h3>
" k+ l0 s8 z, G1 k1 O; k<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>- `' b, ?( a1 M7 U) V& |7 ]
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>* x( c! ^% G6 W
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>% E* }& b0 v% @
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >; l8 z2 T$ y$ T) A) P
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>6 i2 {* B$ o- S% b
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
) ?% x( d  W0 B<h5 id="1示例代码-6">1、示例代码</h5>/ @5 U2 p+ m* Y7 P; c; j- V: ^2 _
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
3 v3 z5 R8 ?* a; W' g    // 通过主键查询学生信息
# t' s# B- W; ?0 I6 O- v    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
% S! e3 U3 c  Z1 A% w    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);1 Z, X8 @/ R  D2 O+ a, Q) \. C) A
    // 查询匹配关系
- n4 U. f& Y) O& S    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
8 Y9 T7 P6 [; ]4 o$ F% Y    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
# U: S# l/ |& h! p    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {# |, H  D: f4 o
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
& c; i4 m& ?2 p; ]: g        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
  G) O6 |7 J! w* l- Y6 n$ ?8 @        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);1 y7 Y3 c1 I- w
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
! r: ^% d5 j1 T( n7 O# V+ K, X- G. r& G        studentVo.setSubList(subBoList);
* w$ t* N, M; x, _    }( a  Q" c' K/ e% A7 {& @2 X
    return studentVo;
8 A8 [: K# ]1 a, Q}4 G- q7 Z& B8 R* K1 i  ^7 P" i$ p
</code></pre>
* J9 j* C& x$ U  `( T$ \, j7 D' K% n( s<h5 id="2理论分析-6">2、理论分析</h5>
( z. U) r6 h' y<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
% o! C1 B1 m& B: H# {) \" ]+ o<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
' ]$ g9 V) f* ]8 q- t<h5 id="1示例代码-7">1、示例代码</h5>
5 w2 C" n% |, i# m0 u2 H( F+ o<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {( W! x- P( D1 U# O8 w) Q
    // 通过主键查询学生信息
8 G+ u5 s" X$ S- M3 A0 x5 {0 q    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
: [8 {5 d! ~# V    // 批量查询学生ID
5 D  D+ m: L/ _/ ^4 \: ?  t" M2 z    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());/ x. [1 H+ E7 p+ @! u$ z( A. K
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);: t* Z5 `, e( `( S; w
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
: ~3 E- ?, }3 n# |    // 批量查询课程ID  A8 A+ T- F8 B: {
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
$ N; X) q1 Q5 L/ s1 i    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
' `" G& i  T. y+ j        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);8 j! F' i; H3 ^2 W% S
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
9 L6 h  y$ {7 o! v/ P) ]        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);2 i* }2 M( {( q
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
" j; d5 l( d  k% _, q+ O3 T  v2 F        for (StudentVo studentVo : studentVoList) {
! e3 A. O; q2 c            // 获取课程列表
! E6 E1 r3 [: Q; b8 p, z* e' l            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
$ ^2 _% `8 C% O" n3 k8 z" `2 w            // 填充分数
" d: q/ }% I3 E2 w- V2 q& q            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
: u- U+ L' R% k% ^0 v9 F            studentVo.setSubList(list);
& X! K. u6 o$ ^* G* G$ z$ [$ Q        }
+ l& W# G6 m- r4 p3 r/ E  I    }- {1 D& q$ b+ @6 Y% m' r: P2 W
    return studentVoList;( H  E3 J+ O+ z- `
}0 C+ X' @# i$ r. u9 a/ M
</code></pre>% O. y5 O: G. ]! v+ h" U& E+ C$ L
<h5 id="2理论分析-7">2、理论分析</h5>; I) D- l7 z% G
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
% O9 \3 E3 W$ t<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>* U: D* W/ x) j' h6 i) M2 O
<h5 id="1示例代码-8">1、示例代码</h5>1 `2 [. \& Z# ?$ k2 q" _) F: O
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {1 M+ {! v+ m3 J
    // 通过主键查询学生信息
7 V. t# n/ ~! x0 h    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
: N8 H9 i  M& K2 ~  g4 d$ J    // 批量查询学生ID
1 [" o' K* t" s* N) X/ f4 Q    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
4 e, t  q' R9 u0 Q$ R) A0 E    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);+ k# K3 c/ z9 I3 L: ]  ?0 F6 R
    // 通过学生ID查询课程分数
1 A! `6 n2 U6 g5 h, y1 m. G    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);7 t1 _: b2 ^1 t4 U
    // 批量查询课程ID
0 U: B' D& F8 s6 f( z  x# I# v    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
* m* E  S  ^1 c4 n* U  c    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
4 f2 F- p$ e% U# \4 p8 d5 z# |        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
* a) z# ]% y; j* S' J        // 学生ID查询课程ID组# K3 @" z6 R& M5 @* Y( H
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));: s; o. r- g/ X% t" R* z- Z

7 U" W3 r3 R& M6 L$ @% u        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
& T# {6 y5 ~5 z; L2 g$ B! G- [        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);3 N2 b6 q1 U+ p
        for (StudentVo studentVo : studentVoPage.getRecords()) {7 I( @$ M1 g8 D! u$ f; {
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));3 d& A4 r9 @: Q+ e) k( t
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
% ^$ e) u! O6 H( `: e            studentVo.setSubList(list);, Y1 F4 I, x2 B
        }! D, x5 |( {& i! b" H
    }
0 [# e  [7 k& p& P" F( W    return studentVoPage;7 V! C/ O% B" [+ k/ ], D6 k; k
}
9 x1 h% S# c9 |4 O3 D/ G; ?</code></pre>
/ q; c% j) t, ]4 Z<h5 id="2理论分析-8">2、理论分析</h5>
2 A7 C! b5 t/ T0 P( J8 v<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>7 g* s# d4 G+ Q
<h3 id="五总结与拓展">五、总结与拓展</h3>/ M$ ~8 t& Q  E' b
<h4 id="一总结">(一)总结</h4>" S2 N- Y; Y8 ]
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>3 q  a' x: }. b1 Y* ]
<ul>; [* l3 i" t6 M" r% w
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>7 @( I! t* D8 W( Y
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>2 p0 Z" H7 v( o! i0 j1 M
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>7 N  [. [; z7 d( X
</ul>! L, ]5 t  {  j, \( {
<h4 id="二拓展">(二)拓展</h4>4 p7 H0 ]' {3 q2 M, ?" r6 e! ^
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
% I( M2 F: z7 O- j  m<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>1 j7 ]- b# z& R; R4 a. F9 I. n
<ul>
$ z; J0 T* x$ j" B9 b% H9 d+ E' _2 y3 R$ E<li>当数据量较大时,仍然具有稳定的查询效率</li>
& t4 C3 P/ Q0 I</ul>$ o4 X& I  S7 ]
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
" |1 q; _  l2 f$ M: P! k, H$ Z$ F<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>0 T7 i$ b: c. ]( r% A7 |
<ul>$ Y  v# o7 ^2 x( ]
<li>与二级缓存配合使用进一步提高查询效率</li>
5 M9 q6 H. V, A" `4 i/ n</ul>
: w0 ~5 q3 M/ p& Q7 c( S4 n$ v$ j<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
: ^) p! j6 q  d<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
. w. k6 ?; w$ ^# D! k9 D
/ C0 l% V! u8 ]
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-1-14 05:12 , Processed in 0.064008 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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