飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8049

主题

8137

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26477
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
0 i$ j3 j$ q1 _. D& E
<h3 id="一序言">一、序言</h3>
! E% t( W. P4 q, n3 o<h4 id="一背景内容">(一)背景内容</h4>& |$ V) H3 ?) a' S
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>3 l: x8 B6 H9 t$ [% P" p
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
* K/ s! Y* y$ ~: e% N% d<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>" D8 |" v" e4 P' B
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
; C) F1 k* B! q$ x! E<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >/ A$ @' c  ~: u1 y/ S0 w
<h4 id="二场景说明">(二)场景说明</h4>
* z1 p6 {2 @% N3 Z5 E- E; R<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
0 c# w0 s0 ]! O; H5 ?; A6 P<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >& E& M2 e) |$ V  A, x) n: B
<h4 id="三前期准备">(三)前期准备</h4>
! x  u  }( i, W6 |& a<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
2 C5 F' @1 o' f2 u6 m<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
: L6 b: p. d* W# i" d<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
  F- j, `! h/ w$ b<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
1 H9 v4 M, E* F3 `* r+ W<h3 id="二一对一查询">二、一对一查询</h3>7 v& x) f2 |% O# m
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
" u/ j, {1 l0 m4 U<h4 id="一查询单条记录">(一)查询单条记录</h4>
. j3 M6 `5 ^: D* C, v/ Z" n1 s5 `. E<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>" e4 V5 v0 t" O: T7 Z' j3 ~: }
<h5 id="1示例代码">1、示例代码</h5>
0 w6 F6 H- d% x# w  A8 S5 J3 j<pre><code class="language-java">/**' S8 Q) E4 U0 ^9 g& W8 b
* 查询单个学生信息(一个学生对应一个部门)1 l. M) s$ N. v& _0 I
*/
7 i- T6 `2 T7 h% n) m+ X2 o$ \' Q1 Fpublic UserVo getOneUser(Integer userId) {0 q3 T; M1 r# ^1 H. {! d. n
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)& d, f% ^" P( j' l2 v
        .eq(User::getUserId, userId);! j# d; b/ g% F% [; @1 \
    // 先查询用户信息# ^. f- Y% J7 I" q2 J/ v! T
    User user = userMapper.selectOne(wrapper);" Y3 t' Z3 U& g/ [9 e( E
    // 转化为Vo& `+ X6 E9 ^: u6 k
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);7 a& l3 k) N1 m9 i
    // 从其它表查询信息再封装到Vo% l$ ]& }1 A7 z7 z7 J# `
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);. m+ ]  {# q2 y( g& V1 q" X# w! h& X$ ~
    return userVo;
+ [9 K9 n  S/ E. Z& u}, y( S% K6 R, r
</code></pre>1 w: b2 D- w/ ^7 V& y2 m
<p>附属表信息补充</p>) x8 w6 w" }! `. n  _5 g
<pre><code class="language-java">/**7 G; e8 \) D2 z7 `- b
* 补充部门名称信息8 j, L5 Z8 `( D% \* }
*/' u2 T7 |* o1 Y' m. ~
private void addDetpNameInfo(UserVo userVo) {' j. j- I( }1 {
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)# [, ~9 W( t( k+ l! U
        .eq(Dept::getDeptId, userVo.getDeptId());. [. G+ z2 R$ q7 [6 D
    Dept dept = deptMapper.selectOne(wrapper);
5 E$ k: X  w* ~/ b    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));% m0 j+ G0 h. E/ ?1 w
}$ Y: o- V* ~7 v) w
</code></pre>& {/ O( M5 h' ]; [# H1 F- O: I7 X
<h5 id="2理论分析">2、理论分析</h5>
0 p" ]" k+ F4 J<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
" S& J( a+ C5 Y! Y7 R) s: m( Z<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>% i: H- C/ {& U+ P9 y# @
<h4 id="二查询多条记录">(二)查询多条记录</h4>
& G3 ]  ?( R# M. o; P  K0 X<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
& l8 P2 N' ~& @8 B6 u; M" d- a<h5 id="1示例代码-1">1、示例代码</h5>
8 ^- r& M7 J2 l- c<pre><code class="language-java">/**$ O- x' q7 @3 s& `/ q
* 批量查询学生信息(一个学生对应一个部门)
% t! a0 D4 P$ X1 `: c) C' A */- a. A/ l' W0 B- _: ?* j3 j
public List&lt;UserVo&gt; getUserByList() {; D5 {1 u+ y9 ?1 N. n- R8 ^  J" @+ ]
    // 先查询用户信息(表现形式为列表)
2 l( T$ Z0 \, H7 j. H9 ]# B    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());/ a4 J7 E, x( e0 f$ ^3 W
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());6 E' s6 G. T1 l# M# ~9 d
    // 此步骤可以有多个
) V; Y- p' O" _0 {3 |+ k! \    addDeptNameInfo(userVos);
6 U8 V7 T% s+ M    return userVos;4 ^/ R1 ]' G$ U1 b1 d+ r% E
}  M  ?; d. M8 ?) O
</code></pre>
. R6 M4 l0 [3 [1 B3 b2 B<p>附属信息补充</p>0 D9 M; c, b! Z) P
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {  O, d8 Z$ Z2 `7 ^1 ^# F
    // 提取用户userId,方便批量查询
( ^4 J. r5 P  R/ k6 }3 m. J, ?    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());3 e9 M& i" A0 D- Z+ {0 g
    // 根据deptId查询deptName(查询前,先做非空判断)
5 B- i) L+ s5 D    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
$ t, g# i  c* d. c. l9 }* s    // 构造映射关系,方便匹配deptId与deptName
( p# t: [$ _: u. b    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
0 Z) ~1 ?# V" X9 `  J    // 封装Vo,并添加到集合中(关键内容)0 ~  M! D* d' ~5 W" \
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
; M( G; g/ h" I* F4 t}) o2 \4 ]. @9 G) {8 l
</code></pre>
7 D- ?4 ~0 \- R<h5 id="2理论分析-1">2、理论分析</h5>7 r9 T* W' Y0 y4 B% w6 D2 U, I3 Y
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
3 a, m0 R6 a  i$ x" I" l/ D<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>" z$ R4 e. q& d. B7 |4 q! k
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>* W3 o' X/ v, E! Q9 N
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
0 d/ B2 d, |% l( v0 h1 @/ J<h5 id="1示例代码-2">1、示例代码</h5>
: d1 Q0 M2 C8 F% j9 w) o3 [<pre><code class="language-java">/**
* a; p! I  }6 [/ I+ V * 分页查询学生信息(一个学生对应一个部门)9 g2 z4 t9 n1 n9 @" y& @
*/( S: x# q# n3 L# Z, b+ j5 u
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
: s7 U" d' F* R* k- d6 E; b    // 先查询用户信息9 T! B0 W1 b4 x* w8 {# w$ i4 c( {
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());4 r1 t6 }* @1 ?; \  h
    // 初始化Vo
# F* ]1 V( a0 b9 l) n, X# l1 n    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);6 _3 o; L7 x$ b9 v% J
    if (userVoPage.getRecords().size() &gt; 0) {
  p( J4 s3 M3 g: I0 f4 ]        addDeptNameInfo(userVoPage);
5 P# h9 I7 b) H% c9 Z    }
- V9 i" Q! \3 m) d( Y1 `4 R    return userVoPage;* ]- z: n+ M. s' z2 S  a
}
# Y8 w3 `5 e6 b  s' y$ k) D, u$ I) K</code></pre>
" }; e' j" m$ c9 W0 y9 j3 A; `: W<p>查询补充信息</p>
' w7 H& r/ ~+ ?; r  b<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {  G$ D, }6 d+ P* o4 D, \5 V1 U% q# S
    // 提取用户userId,方便批量查询/ |# U. N. [7 ]* R& r1 `6 N
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());* H( \& ^0 ^$ n. b: O4 i
    // 根据deptId查询deptName
- f$ a$ r0 E  }, V: _    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
5 E0 |0 d; i$ H& t& s2 n. I! h8 G' G    // 构造映射关系,方便匹配deptId与deptName5 u( A0 S6 K' [' o5 w" z( c! ]2 q" O+ b
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));) }6 k  L& K; }. e* @
    // 将查询补充的信息添加到Vo中/ a9 x8 _3 {. q+ U4 L  d1 A
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
0 D# c  l/ L! O! d$ z6 u% a}7 U, X' y: k' H/ q0 }
</code></pre>5 z3 w( Q6 Z* ~3 V- B. Z! q
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>! K+ z- R7 Q: ~& V2 `9 s+ ~
<h5 id="2理论分析-2">2、理论分析</h5>
" f4 A) I1 `$ [<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>. p& F2 y! ?6 s' s0 H- U% C) l$ K2 ]
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
( l2 l+ x' M* \" x- o& }% @<h3 id="三一对多查询">三、一对多查询</h3>
; K4 J8 j2 n/ ~* L5 }6 t$ `( H<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
) b! s1 @+ P% j- w<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
6 h1 c7 _+ q) p1 D<h5 id="1示例代码-3">1、示例代码</h5>
' z' c$ f3 x8 \6 Q1 c<pre><code class="language-java">/**, N. ?! o2 J% ]: b! u
* 查询单个部门(其中一个部门有多个用户)
; [" f" w$ `5 u: x4 {5 u */
. _% L$ s7 |0 T5 E( |public DeptVo getOneDept(Integer deptId) {9 b# d* J0 T1 d
    // 查询部门基础信息; o* _/ C5 s9 v4 I# P! s# @+ X' ?
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
: [8 f9 \$ I' b" g- u- [, l    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
. a6 V% m5 a% b: K$ _    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
3 U8 _+ g- ]7 n. [7 x. b2 N    return deptVo;
& i& \+ @8 e  {. O+ ?9 E! C}
* {; v# F9 {' S' N$ p</code></pre>$ [8 w6 Z. R: V/ C5 C
<p>补充附加信息</p>
( ]2 N) ?8 g3 t4 v4 I1 f4 E<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {. I6 Y! E; x+ d4 N
    // 根据部门deptId查询学生列表
  k, F" x# b# K  p4 K    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());  E9 f! E! u- ]- `* E: j1 t# ~, j
    List&lt;User&gt; users = userMapper.selectList(wrapper);: O) n1 j0 Y! c
    deptVo.setUsers(users);
! u9 L: J4 {8 M; B$ x}
4 p+ v1 o! m6 x" w7 A! B</code></pre>  Q, r5 P+ ?" l5 d4 t) ]* X5 M% E
<h5 id="2理论分析-3">2、理论分析</h5>
8 z" B: t' n' |: A+ A7 j- \<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
0 x6 j, a( n' O; u* h, n<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
- j9 ~6 [( j9 ^$ q6 O<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
8 v* F/ V2 b# z+ N/ Y9 g- Y<h5 id="1示例代码-4">1、示例代码</h5>
) t" v. R# X" B, C5 N<pre><code class="language-java">/**
* h0 O  w' X0 }8 Y * 查询多个部门(其中一个部门有多个用户)
7 [0 Y0 w+ q( m  x7 C */( @$ Z% {! |' i& @
public List&lt;DeptVo&gt; getDeptByList() {
- s% R* V! M0 N    // 按条件查询部门信息0 U$ L% y5 I* g% _2 b) K1 @8 Z
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
! k  Q8 ]2 w  V    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());) e* a9 T# F& n  m% m) \6 O& U
    if (deptVos.size() &gt; 0) {
- n2 r# ?" i. X7 d        addUserInfo(deptVos);3 V5 o" K+ J' O' j$ f
    }) ^' L% D. S; t) L, \
    return deptVos;
1 E# O4 y# {% Y2 ]4 n}1 f0 h% u: u0 j* H' D& H
</code></pre>- O, g, n4 L+ p! B9 j5 J
<p>补充附加信息</p>
; D, Q* A4 w9 d( n<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
0 G& K: p! T' d/ s    // 准备deptId方便批量查询用户信息
+ w1 B( e( z7 d3 [. r' L1 z    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());5 I* V' w  h4 u% w; X3 i! Q
    // 用批量deptId查询用户信息
, q: {' ]0 K& O    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
1 b, ]7 R* q1 i! c/ @+ {+ d4 |    // 重点:将用户按照deptId分组
* @* J* v* I$ L3 P+ o; U    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
/ o% s  Q/ Z; B1 ?$ U    // 合并结果,构造Vo,添加集合列表3 H) m! U+ D/ V2 \; J8 m8 S
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));7 r. s, r* z) S& p
}' G6 p) @9 r# x( J2 G, m
</code></pre>! R8 a( r! O+ P3 W, I1 \
<h5 id="2理论分析-4">2、理论分析</h5>2 \3 h8 Y) G6 ]6 n1 @8 v
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>6 k' v% X$ H2 J0 f/ w
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>% q0 a1 D8 T: @) X& x( [5 l
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>+ A3 e  r5 L! N3 r% m* {1 y
<h5 id="1示例代码-5">1、示例代码</h5>
7 w9 h/ n9 G& J<pre><code class="language-java">/**  Q- V8 r. a9 A, V) h! @
* 分页查询部门信息(其中一个部门有多个用户)
/ L) a: I6 o* b6 |4 n6 H */7 l0 K' _+ T4 r. g, ?' h- D5 h) Q
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
+ W' [  A( s1 e' C. B    // 按条件查询部门信息
* }+ m( E& g, U6 c6 J' Y" n' b    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());+ F4 w+ Y; y1 y) l! K
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);- T% l$ B; [( P& M3 ~0 _* H
    if (deptVoPage.getRecords().size() &gt; 0) {0 s. u- {! }, W. p
        addUserInfo(deptVoPage);' N' ~1 V0 I6 S$ N7 J
    }
: z- o. [# y; H9 _# s    return deptVoPage;
1 U; y6 p  S1 P) g0 C5 w' p}- k7 s; w& C. T% Y7 F1 \, p3 X
</code></pre>( d* d$ f- t  o# R, ?/ Y1 l
<p>查询补充信息</p>
; t9 r# e( Q) B* Y" V& E, A! D+ H  _<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {/ Q' M( _% f0 m/ H: @: M1 N
    // 准备deptId方便批量查询用户信息, A4 I5 F' p7 q( o: K& [
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());5 `1 V8 u  e% c
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
) Y& _6 {% [; A) b. Y) e    // 用批量deptId查询用户信息( ^5 A1 O1 r: k! q5 g
    List&lt;User&gt; users = userMapper.selectList(wrapper);
: m: c* u. d3 ^; x% ]4 `    // 重点:将用户按照deptId分组. r* u/ Z! z: F$ D: G
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));' V5 e2 M$ r' L& K
    // 合并结果,构造Vo,添加集合列表7 u4 D' \% F6 R* O
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
0 Z6 y+ w0 f2 E+ ~/ ?}
2 p- A0 N, ~5 Z</code></pre>* x* n* [- X0 e& ]
<h5 id="2理论分析-5">2、理论分析</h5>  v% h+ e9 b& O2 p) a
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
) _0 \* [9 f2 Z9 y7 n" d8 ^<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>& g$ \$ g! Q  j  M
<h3 id="四多对多查询">四、多对多查询</h3>
( k, S" L; C$ e- p9 L5 F0 w<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>  q/ ~8 a; U1 Q! k# b1 U% L
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>. p* q5 n4 D! ~6 `$ N- }
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
  K: ]# A' O' w' x<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >6 F) O$ J2 f' H* e/ D
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
5 ]' D! W$ u6 k<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>* t$ _0 @9 ^$ L8 k/ j
<h5 id="1示例代码-6">1、示例代码</h5>  w( m# B$ B/ v) t$ k, z4 x
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
" S* O6 w# g0 A' g    // 通过主键查询学生信息
- E3 b6 s8 L* N2 H+ A    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);0 Z0 H1 _$ J! L5 K# E  H2 ?2 W
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
- x0 w* ~5 U1 f( _    // 查询匹配关系1 P7 X/ ]: D7 r. e
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);3 F4 `( b( g! E7 k5 y6 L4 d/ M! S
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
' ?2 V1 n( P& e" [    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {: w3 E% h2 ^& Y! q: F
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
. i7 j& a& x+ o5 V" w+ j' N        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);, d+ f3 x& s( }6 Z! ?
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);- w& x& x* V* r) |8 n2 R
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));& I& F- t+ m4 g1 x  j0 t! I
        studentVo.setSubList(subBoList);
- K$ U3 v4 z6 C8 V# ~- O  |    }
3 x, M& V; d  o- h' y    return studentVo;8 |% B  b; n6 A
}
; p9 G+ P& V: \) R. e' d( y# O</code></pre>
' A; C( V' a3 G! U( \<h5 id="2理论分析-6">2、理论分析</h5>9 N( Y0 K" ~5 t+ C& \
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>. ^- t- e$ A. A& j# s
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
% J: n7 T7 m6 U2 Y3 n<h5 id="1示例代码-7">1、示例代码</h5>
4 A& N$ N8 M& f<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {( g+ j+ w6 s6 G3 g  ~, u$ i" }$ X# C
    // 通过主键查询学生信息
% b) S: u7 @3 C. `    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
. Y8 c6 j" k" e/ @. e  x9 P* T$ B7 q    // 批量查询学生ID
2 n1 v" }" b% e$ v( \+ C    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
: B# N; I; E' m) k: k% J" J* z) f. U    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);" J$ S7 ?9 ?6 j8 b& L) E" e5 g
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);8 ^6 \1 e3 D, L! ^1 }3 e5 a. O
    // 批量查询课程ID) Z6 A$ s/ ^* z/ b$ ]4 D
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
; t* o7 P& ?" ?! A  o    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
$ K3 u4 w- ~" l" ?8 g        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);, p- S' X. I  h
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
& z" q5 \2 {: |6 o' w        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);" o5 e# m5 h9 o; c! O
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
( p* E- B$ J: A4 {4 d+ X4 s' Y5 a        for (StudentVo studentVo : studentVoList) {
! C6 M7 B& G( l' X" f& c            // 获取课程列表
2 ^/ C7 l6 y6 a# E, c( ^            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
8 f7 R  ^+ v4 d            // 填充分数
3 Q; n  S/ E: ]& R: T3 d* w            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
% x; ~9 o% _7 {+ ]+ j) `9 J7 D            studentVo.setSubList(list);
7 R4 G. B7 q7 r! ?$ U0 ]0 w! l' }+ l        }" ?" E# k- Y$ q- i& s) q+ z  z
    }
- p" X& U) `( Z% R+ ?3 ^4 j, n! I/ L# b# R    return studentVoList;
. d# ]2 ^6 E$ o& ]3 D9 n}
7 \" ^) v( l  N</code></pre>
; D7 {* R; f4 B1 w( y. r! r<h5 id="2理论分析-7">2、理论分析</h5>
: g% S, L9 }1 X3 p<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p># Q1 A$ |/ l# \( s
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>  L6 g& [! ?" M" n5 g! o0 t4 x
<h5 id="1示例代码-8">1、示例代码</h5>7 A8 T0 K) ~" G2 x
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {3 j' L3 I2 K+ d0 S4 S1 ]6 @  o( |" s
    // 通过主键查询学生信息( F4 s# t# y" Y, J: N8 E% o, G
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
( N5 r1 {3 H! D1 [  Z% O    // 批量查询学生ID
0 ~0 D; i* m! t0 i    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());, s5 r1 W; k( e" D8 {! a6 h
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);& P- Q7 c0 v6 G7 T8 G# w
    // 通过学生ID查询课程分数' T. t/ j3 c& b4 j4 }6 u) M
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);) J4 |% G& _( D; U! z
    // 批量查询课程ID
& @+ V1 O. U+ S& W7 o    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());" Q9 R) O( B2 H) r7 q  I/ |
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
6 q1 M$ J  a' \, n. R1 V        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
: i7 w( G& z' n: d% K        // 学生ID查询课程ID组
/ `6 b! a# A1 N        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
# F- w+ W) ?; a5 f$ ^9 C
% F! O: r: g% W        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));# Q7 e/ E  V( h
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);: \& Z' S0 C) Y2 h2 w
        for (StudentVo studentVo : studentVoPage.getRecords()) {
; S( x2 K; w' [" B8 ?2 ?            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
) H/ |5 t! ]2 n; `2 c# O$ H8 ~7 T            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));2 v9 c; }3 w3 d. @
            studentVo.setSubList(list);
7 x  X  q8 c- c* H) {" \        }
/ p6 T/ h6 `) t- ^/ B( @    }
; `( ~/ L$ a' z8 \) D3 ?    return studentVoPage;. Z: ^* B% i7 Q2 B
}, e7 h: n) u* T2 J. h5 g
</code></pre>% Z9 i& D- s: ?
<h5 id="2理论分析-8">2、理论分析</h5>, Q- ^4 @* t; S! N1 w3 U/ P
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>% `1 Y* J1 [% P3 k
<h3 id="五总结与拓展">五、总结与拓展</h3>5 N6 }+ O( M2 H& |0 q
<h4 id="一总结">(一)总结</h4>
7 j' W' j% G% x  b) H<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
6 ~& Q7 N4 {( Z7 K) u3 b<ul>- z. ]. r6 Z5 z, {
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>2 o: Q+ o/ z3 d' W) S" X! h8 x
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>& A" u$ w0 @& v& N+ W1 X
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>* r8 m; o# J5 Z; o7 c& Y& w( R
</ul>0 Q, \" _3 W2 H/ J4 `
<h4 id="二拓展">(二)拓展</h4>
& c* L+ B! Z/ r4 M- \% P9 n<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>8 U6 t" ~( z2 k3 p
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
  N9 _% F' q- p1 g4 Y; S<ul>
1 z- j# j$ j& d: R# F; v<li>当数据量较大时,仍然具有稳定的查询效率</li>
& i, L  m2 i$ i# K. g* e</ul>( g. j. w3 Q6 d+ ~2 X. n8 s
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
, O+ J+ }$ }2 K  \6 y<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>1 a, c% r7 H3 [! s3 o. X( \
<ul>7 f- X' f  Q  H6 h2 @5 o! U' X
<li>与二级缓存配合使用进一步提高查询效率</li>
- w( z7 J" R, B0 f9 i% D* v5 M$ E</ul>
# a& }% F: ]$ w1 C" \<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>& Q' k; D8 V4 C! R* b0 a* p- Z/ H
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
3 |- J: Z) o; V1 h1 O  G5 F
& R: Z2 J% Z& |9 L0 @& |
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-10 15:14 , Processed in 0.067710 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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