飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8038

主题

8126

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26444
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
0 Z) f$ O$ R6 ?
<h3 id="一序言">一、序言</h3>
# f5 t  {. G- Z+ T4 q- s<h4 id="一背景内容">(一)背景内容</h4>" ]6 I  L! Q% V1 M5 A, Y( n! _& |: E
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
' ]7 _. G; I7 E. C7 {<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
* @' I* J/ \7 }( j<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
  t8 T$ j/ K9 J( U: O3 p* H<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
5 s& v' j' l. W6 t  ?' _' ]9 t- b; [<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
$ c# \4 ?7 N. W1 g<h4 id="二场景说明">(二)场景说明</h4>
( ~* @% h: L% _1 E) }<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
& U  k  n2 t+ s0 v* E/ O<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
0 L, Q) T6 O. e+ e<h4 id="三前期准备">(三)前期准备</h4>' J  |. z! ^( S& c; b: a1 z
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
& S( G7 l0 d4 t. k<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
9 X6 e" i( b$ s  u<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
  I4 X& `. c- ?. S<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>: A. `  D2 @6 e+ y
<h3 id="二一对一查询">二、一对一查询</h3>$ {( p- k# A& L) U) O8 u
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>5 g$ h" r' r! E$ S, ?3 x& I
<h4 id="一查询单条记录">(一)查询单条记录</h4>
: u8 o7 @* d8 ^% c: f<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
8 O* p5 y% ~# Y<h5 id="1示例代码">1、示例代码</h5>3 J# T1 d0 k* H% S  N
<pre><code class="language-java">/**
' D; B! c8 }' Q: r% ^6 c * 查询单个学生信息(一个学生对应一个部门)
5 |3 |4 v) y2 e5 _2 E* k* }# F! B% P */
0 A% u9 v* t& Spublic UserVo getOneUser(Integer userId) {! z9 G! g$ l4 i, V  X$ @9 b
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
; a7 r3 p# n) K8 \' g( D0 t! `        .eq(User::getUserId, userId);( G) _7 ~# V+ G* @! I
    // 先查询用户信息
  H6 H' [3 W1 T! F7 C$ ~    User user = userMapper.selectOne(wrapper);! n& q) i* R3 S
    // 转化为Vo
! W% q" z* ]- R, C& _1 ?$ X2 L7 L    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);% m3 v7 |, k2 W; w
    // 从其它表查询信息再封装到Vo6 q( k& v+ v" D* o2 V$ Z' E
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);2 C8 ~6 E& {- `# O' A
    return userVo;
0 [! w" M) {" V% k8 F}
8 C7 ~7 R2 H' A6 S0 t/ V5 i( v; s</code></pre>4 t) }6 X5 c! [  |7 i
<p>附属表信息补充</p>
4 B) v) n; s. O; R<pre><code class="language-java">/**
# ?, u. \' y0 o8 Z% x7 B * 补充部门名称信息
" ]4 J, A, @1 t/ x */
7 y8 U! I/ R7 H0 Cprivate void addDetpNameInfo(UserVo userVo) {
) l# {+ S# ^6 K6 Z    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)# D/ H3 N- f- s# D5 I3 L
        .eq(Dept::getDeptId, userVo.getDeptId());* n. }- l0 c; x( Q% `5 z8 O3 ~
    Dept dept = deptMapper.selectOne(wrapper);
3 m4 f* j- L  h" @$ \9 m    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
$ d  [3 X- e2 W# w}- G2 @' C4 v' `& r6 b# y/ L8 C
</code></pre>, b, A0 X# G& \2 v; i. w/ J
<h5 id="2理论分析">2、理论分析</h5># p# E' w- N5 |0 a3 d$ T
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>! ^; c6 |- C( U3 _2 K' H' I
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>* _8 I  x( E! o3 d
<h4 id="二查询多条记录">(二)查询多条记录</h4>
- p; S. u  U' q& ]$ \<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
/ e3 h4 \& N1 A% z- ]<h5 id="1示例代码-1">1、示例代码</h5>* |  n0 O$ Q/ Q1 h
<pre><code class="language-java">/**
/ ?: C+ N' q; t' q/ q; K * 批量查询学生信息(一个学生对应一个部门)
% u: C1 i7 B8 P9 P- `7 h */
; l- U" K* X: g: y5 kpublic List&lt;UserVo&gt; getUserByList() {0 Z3 D$ p  k# Q8 S/ N
    // 先查询用户信息(表现形式为列表)+ ~5 [1 l, l, w$ }( }; y2 \: q
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());, D* W* i6 Q, v! q4 T
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());: K# u1 Q. r: Y$ D  G
    // 此步骤可以有多个
9 E! j! ]/ J2 ], P8 j* ~. `/ j    addDeptNameInfo(userVos);% r6 A3 r0 q2 }9 J
    return userVos;
" ]; c# |' y, U}
1 h" Q. N7 [. P  M- [" k</code></pre>
( H2 N" E5 ]3 a# J7 Q- @+ ^<p>附属信息补充</p>
' }2 P3 H+ }2 b1 e4 }4 _- \<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {9 ~7 ]+ ~0 m3 ^" u8 y, P
    // 提取用户userId,方便批量查询! }6 }1 T6 j2 P' {  ^" m) T2 |0 M
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());2 Y# d0 ~/ d5 D/ F; ]* F) h! t
    // 根据deptId查询deptName(查询前,先做非空判断)
7 T) V* q0 s$ E& J, Y4 |5 V0 d7 @    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));, \8 C0 y) ^2 p- z; c
    // 构造映射关系,方便匹配deptId与deptName1 ~7 `+ N" O, h
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
+ e# B2 t7 L9 [8 T- m4 Y5 `) s2 b    // 封装Vo,并添加到集合中(关键内容)
- C# E' y' O+ W    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));, x) \5 r, [0 v( j
}
6 P0 T+ `: b$ H- j</code></pre>
( M- B  R9 ^: V: b0 v9 w, v4 N$ D<h5 id="2理论分析-1">2、理论分析</h5>) f- J4 Z6 v# ~+ p
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>2 Z* x( I( k1 Z% F0 P- c. ~* R& a! r
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>& J. m! @' t0 w& k
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
7 Y8 l1 j2 q) u, d<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>, m" d+ v: j: C- `0 [
<h5 id="1示例代码-2">1、示例代码</h5>1 L$ a" j) y9 ^. _% {
<pre><code class="language-java">/**. Q' R% D, R# v- ?- _. N
* 分页查询学生信息(一个学生对应一个部门)
3 t' C/ ?" @6 e *// s4 a: C' S- `& R% Y( M) g7 _
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
+ u% W/ ]6 X& E$ U# {) c9 ?  E    // 先查询用户信息6 Y0 t# I# h( |
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());, l+ w9 A/ S- i4 s8 x' g
    // 初始化Vo& b3 {$ A5 R% ^0 x: \# Y
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);3 U. j7 ]  s& ]. v" |4 d
    if (userVoPage.getRecords().size() &gt; 0) {& t* x% `1 a2 D9 z) J
        addDeptNameInfo(userVoPage);
+ ^1 ~+ I* }/ {" }    }3 x- }% \% {. s; C9 c7 k* `
    return userVoPage;5 |0 V# n5 U) ~- M
}$ v( K7 R2 `  |6 a6 x8 [' Z
</code></pre>  _, q/ K$ f( Z; U: U0 g0 m
<p>查询补充信息</p>
2 |1 I- L: H# i$ N$ ~8 b5 s; a<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {6 O+ g5 i0 d3 a/ Y) l
    // 提取用户userId,方便批量查询9 R. Q& i2 E8 t% d2 L# ?0 ]
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
& L+ `! y: t0 X" Q; V    // 根据deptId查询deptName
; E; z- z# v7 s    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));) a+ n) X% n, o
    // 构造映射关系,方便匹配deptId与deptName
: Q% i8 }3 ^& E; g1 m* n    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));7 h; T* o. |; G! N2 F) }* T# z
    // 将查询补充的信息添加到Vo中! N6 u2 Y& E9 u  j  o
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));  X7 i) p' |! U* K. E( w: ?
}3 T8 `7 [% [- }6 Q% B# j
</code></pre>
: l! r0 R0 g5 H# |  m2 t2 D0 M<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
( L( N& M9 p) ?; c8 T, T<h5 id="2理论分析-2">2、理论分析</h5>
/ A" G* s: k5 g" c; L# A) D<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>4 `% [& L, r( E
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
% G7 W. w) p7 }6 O: m<h3 id="三一对多查询">三、一对多查询</h3>
3 J9 f( ]& [' J5 `: v<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>! W0 K% G: E! |4 q5 f8 ~
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
2 M/ p5 F+ I) V4 f2 v$ G/ q, P<h5 id="1示例代码-3">1、示例代码</h5>4 W) k  p" b& S
<pre><code class="language-java">/**
% {( |( a5 x$ y, V6 l$ O; n" K * 查询单个部门(其中一个部门有多个用户)/ E5 @2 j9 p9 D' m! n( z) @
*/! v2 Y- q& Z. P7 i2 p. r( k: G
public DeptVo getOneDept(Integer deptId) {
, s5 z6 ?2 ^3 s    // 查询部门基础信息! U6 A' V* [* Q
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);( d0 z) |! ?. v1 k# C# k( U
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
( e; C2 \' W7 T: ?7 B* e1 I! w8 I    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
- t9 S8 F8 S: |+ q- G    return deptVo;
% t4 U7 H7 g) \}2 k0 Q" m8 A# z$ x; n: _
</code></pre>+ ?+ @: J8 i) U8 d
<p>补充附加信息</p>+ u: O( c1 U/ P( c1 N8 E/ N
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
7 ^6 D% q) ^! C7 m    // 根据部门deptId查询学生列表) D- G! M$ J; w( N+ p: e% b
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
: O& p, P1 z! R    List&lt;User&gt; users = userMapper.selectList(wrapper);- N, R. v: c/ \8 b( ]
    deptVo.setUsers(users);
0 x, R7 f. D' h2 w, r}! J4 u# W& o% ^: E
</code></pre>  ^, ?) G+ Y3 q
<h5 id="2理论分析-3">2、理论分析</h5># ?: u/ K( G1 ~8 Y% _1 u7 G
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
3 c0 j% p7 w8 {% A) ^1 t9 [<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p># m& T  R- j5 Y* [# f
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>6 w1 e/ _- ]  n
<h5 id="1示例代码-4">1、示例代码</h5>8 T9 n9 o2 }: K6 S
<pre><code class="language-java">/**
  g# a/ E0 y- F% |6 b3 K5 I * 查询多个部门(其中一个部门有多个用户)
" m& z% `; o6 q0 j& d* h */
" u9 [6 R7 z& n4 y$ x  Ypublic List&lt;DeptVo&gt; getDeptByList() {
8 Q/ |1 j9 \* @: c, w* @( E    // 按条件查询部门信息7 t6 o/ d* V  D" h* D1 t; ]
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());  h- g; @8 p( z- \
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());8 Y/ B7 ~& t& s
    if (deptVos.size() &gt; 0) {
: O4 r; G' X- U( h, t        addUserInfo(deptVos);, E& p& R/ s% d* w1 m$ Z0 |
    }
/ U2 d4 }$ x0 P$ h' ^    return deptVos;9 `! O- k( i6 s& H/ p( k5 g
}' b6 B! y$ |( y6 Z
</code></pre>1 H( z8 m  c- L3 ~! I
<p>补充附加信息</p>
) P2 |' ]' p. c. V4 V! F<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {4 _5 C1 Y/ L; `% b2 H! V
    // 准备deptId方便批量查询用户信息
5 L  V; d3 q( \; ?    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
" }) ?7 s: {! h, c4 S! }    // 用批量deptId查询用户信息. i; u7 ^6 y& V/ k) h
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
& f; j5 y4 ]* x    // 重点:将用户按照deptId分组
& J& U2 N4 e5 t% z9 x+ t+ Y. l    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
! c( P  t' _% K; O3 b    // 合并结果,构造Vo,添加集合列表. q9 y3 [. A; ^5 G8 G2 V( N
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));% v1 Q$ U+ }& G
}
5 ]. G% P& p- l# w1 a</code></pre>8 g; S' r8 ?% K+ |6 E4 i& ^5 s
<h5 id="2理论分析-4">2、理论分析</h5>
/ K4 k% O) G2 R2 u, C9 W<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
* D! p, s4 W/ ?. T5 J1 Y<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
9 Q8 W; _. b' A0 Y6 I  s<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
& O( |& I- ]6 y$ f<h5 id="1示例代码-5">1、示例代码</h5>8 W6 U/ B$ u2 e$ Z% \4 W7 O! c
<pre><code class="language-java">/**
- B) R: |: D- C7 w. E. ^1 | * 分页查询部门信息(其中一个部门有多个用户)
" j& M5 A! [( q */
9 X5 q$ Z$ l- F3 ~4 M' M- Qpublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
. n4 s7 ^/ H, i1 l. C' m' ]- ^: f    // 按条件查询部门信息
  y2 _; o& `; Y1 U* b  Q* X% z    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());0 q0 ~/ \( P& U2 A# l$ n
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
/ {) F0 B" U/ x$ Y8 I( k$ H7 E2 M; R    if (deptVoPage.getRecords().size() &gt; 0) {
7 l- x7 p0 A0 b7 q3 u        addUserInfo(deptVoPage);
7 |* j8 K( v& [7 D/ Z    }0 f. J3 y7 y0 u- `6 z$ r4 w
    return deptVoPage;" M& Q6 x$ v7 F' c1 Q) Z
}% p( W  ], z8 l8 ^! @, v4 \
</code></pre>/ {. t! j& F9 S$ u/ Q1 I2 ~1 Z9 R
<p>查询补充信息</p>
3 O0 x' e6 c/ ~5 x$ ^<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {" Z. O* J( T+ w- J- K1 _& n
    // 准备deptId方便批量查询用户信息
7 x" G( f& f% f1 y+ I- G    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());: E1 Q6 y, x  l: k9 h/ X6 {
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
# Q2 Q. \9 w3 n1 E3 Q/ Z# J' d7 V    // 用批量deptId查询用户信息
2 T. B' h2 V* U- O9 _# D, w1 t5 }" D    List&lt;User&gt; users = userMapper.selectList(wrapper);
% M: \3 y! ?' }) P; T    // 重点:将用户按照deptId分组0 n! i6 r' s. Z" v( |; ?
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
% R; ]# h) }1 E+ a    // 合并结果,构造Vo,添加集合列表. ^- |7 D* \- ]/ f4 @4 E
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
% g2 ^' J8 K3 }1 S. x5 _3 I+ R}
- [' E4 n5 ]" |: r</code></pre>
2 g$ ^4 m- s% n8 v<h5 id="2理论分析-5">2、理论分析</h5>( Y; X# w1 F! K2 j' f2 A
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>6 D8 r. M9 T: c$ T) V4 l) o, a
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
" p, s! j% A& f; k! F" Q<h3 id="四多对多查询">四、多对多查询</h3>; u! [/ m4 X! w& C/ u
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
2 o0 m1 t& x  X" D<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>2 o) m; V& t) m1 [' N  @: n, p2 X
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
9 f& l3 `1 W& k% H  z, e<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
0 h) I4 K* s3 T. n; t<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
0 Y$ K* G" V) }" E9 \& B<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
' |4 B' C1 q8 F! @! x<h5 id="1示例代码-6">1、示例代码</h5>
3 E+ ?5 _4 T9 }7 ~- f$ S<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
0 T0 S% w% a/ z& o( r; }    // 通过主键查询学生信息* s$ s) Z/ O4 E& u5 G* h
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
* @0 Y3 b9 y/ {# z# n# |6 k    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);  m0 h" l4 d' l! X/ ~+ Y& K7 o
    // 查询匹配关系
2 e- y1 y5 i; l$ w: q- b    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
& g9 P% r* _. G  C3 f3 z    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());" ~& b$ ~" O8 U
    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
5 V/ c# ^5 L1 E+ e; J! y0 r        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
9 ~( J* e6 v( B, ?5 c        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);2 h/ H) I7 V1 x& Q3 T1 N
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
) ]: Z( @( z) s+ H4 ~9 q. X+ [        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));6 {7 V. s, F) ]- J6 Q9 f2 E6 D1 Q
        studentVo.setSubList(subBoList);
8 w0 }- t: z7 t) f: H    }1 T5 [( q$ q9 c5 I1 [$ c3 {! m' s
    return studentVo;
9 `4 ?& c+ v  |}! Z2 _' A2 _5 T9 W) d1 r' ~
</code></pre>  g' l1 n. q7 f+ I/ W
<h5 id="2理论分析-6">2、理论分析</h5># D, O6 B" d  Y6 t6 ~0 B( b/ A) y
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
: g6 J) h( U1 F3 R; |# B<h4 id="二查询多条记录-2">(二)查询多条记录</h4># M, P! k. @; S. a: {8 K( ?
<h5 id="1示例代码-7">1、示例代码</h5>
" k* m4 T' t0 u) h<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {0 [# K# U5 M6 P
    // 通过主键查询学生信息
4 G) D! O. S& ]3 P) ^2 v9 k/ \% L    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
' b4 r# H+ l. y, Z5 }6 ?5 c    // 批量查询学生ID  j+ y7 o, B0 i0 {) F, \9 f2 N
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
. G4 Z# C5 n1 T* e) l  t    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);  W! ^5 {% ?8 `3 W2 ?& g! [
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
* V! L. M8 A+ p1 g! D    // 批量查询课程ID3 i$ d: O: k. q7 g5 i  u
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
0 |7 f$ A5 C, M* |    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {4 F. c. M( V1 z9 N6 Y! Y
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
  \5 X3 D* u4 L) F        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));! V& ?! R3 b7 F; o+ x1 r; g1 f
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
/ `: {6 k& w2 _+ R        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
' n7 ~3 ^, h5 Z3 T0 [        for (StudentVo studentVo : studentVoList) {3 e' k3 D- C! e! \- m+ \; M
            // 获取课程列表
0 Z8 _; {& j% D) ^            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));1 i" c8 e2 b# D3 x; b: j* k6 \
            // 填充分数
( t8 V4 L# r9 T4 v1 O; E            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
+ p. A6 L6 r; E0 ^$ g            studentVo.setSubList(list);
- V: |( F* v! a+ k        }
& R: z2 G8 a, m1 S9 @. i    }
, I* Z8 I  D  |    return studentVoList;
9 x5 {; f( H  E1 N4 X* x# P) _}8 H! W3 P9 Y5 e% i5 I9 D+ |- Z
</code></pre>. K! |" b; O$ D0 f( ^% F
<h5 id="2理论分析-7">2、理论分析</h5>0 q; F8 U" w* I8 j4 e
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>7 L6 P$ [6 g- u4 {- D( L7 S: e, @
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
# h2 z5 \+ K0 Q9 L9 Y<h5 id="1示例代码-8">1、示例代码</h5>2 R3 I% v% M* `5 e* w& u% w4 ]" g
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {4 B$ i, n" Q$ ~; F2 L  _. A
    // 通过主键查询学生信息8 `( P+ r" b9 D9 h2 m
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);$ O( |5 U  p/ }% @- {! [! _
    // 批量查询学生ID7 W3 @9 H0 u0 [+ c( W4 Z% P- m3 o; E( d, M, c
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());% C3 f" J* A& k
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
( L& f* y2 \! y2 C, \    // 通过学生ID查询课程分数# O5 `# d7 |' N" ~
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
% K+ ^( Z+ D7 a9 t1 c& c    // 批量查询课程ID7 J; M( \6 `) x& x8 U+ q1 h) S, ~
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());* [# ^0 x1 W1 Q$ t; ~2 S
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {! J' b% k' _! ?2 `* @3 ~% x+ L1 s
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);/ G. @9 J! _6 o9 ]  M
        // 学生ID查询课程ID组
3 V: o# a, F4 ~7 G" z& J! L8 U        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
7 J6 [' N5 Z! l7 q
) W% E; Z  f$ R$ h1 u& o4 \" M/ k        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));6 H( x6 `+ Z; U1 b" g! B
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
* X) a) x0 a8 U5 ?3 U* n        for (StudentVo studentVo : studentVoPage.getRecords()) {- m) x; S# H* r, O- n+ {
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
  L0 \. I6 e# g* u! z* K            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));' t( ]9 }, \& W0 L
            studentVo.setSubList(list);
# ~6 i# _) Y. n4 A& W$ m% b        }
$ ~. M: a( G- c. Y5 G  `: G4 v; }    }
8 s2 a$ ~# S8 J' D8 o    return studentVoPage;
  w- y; @) R8 B2 E}% R6 ?: \: i# }  f' h$ J: \; v) x
</code></pre>
, \/ w/ W# \: c7 P) c/ u7 B<h5 id="2理论分析-8">2、理论分析</h5>; ], C% @( L- v6 f
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>1 M! a7 E: ]% X( B" [. L
<h3 id="五总结与拓展">五、总结与拓展</h3>6 b; Q: j: j8 Z, z# ^1 J) r$ M
<h4 id="一总结">(一)总结</h4>
* b  ^' u0 N' o9 b4 B3 n5 p<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
( Y; W& c1 n0 I3 {! S8 m* \0 W<ul>
! j: v$ G* O! G0 Y. o<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>2 O. @* |$ q: y
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>2 c$ f4 ?, L/ }0 P( }! N+ Z
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
! H& ?% B: A7 D3 o</ul>
. m0 W8 ?$ ]+ X# [$ f1 i1 [' [<h4 id="二拓展">(二)拓展</h4>
; S& O+ P/ h0 ]2 _" I<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
* G0 m, G8 q" m0 U$ R1 W<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>1 C& R0 K  [" ~) P
<ul>7 j% @$ F! {# w# n! U
<li>当数据量较大时,仍然具有稳定的查询效率</li>
# s* {6 S4 O% q- P</ul>
" f9 `1 [" i, o0 ~$ y; }: J5 Y<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>" k$ m8 U8 i3 T5 ~" Q( G4 U
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
$ i. F6 z8 N9 H" K( ?" L7 H) z<ul>
/ x3 G7 I) s  D2 d+ S  r<li>与二级缓存配合使用进一步提高查询效率</li>
! ~, o& S! b/ `7 p( B</ul>* h2 D6 e4 }1 t) W: ~, A! w
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
1 V7 [  N% O" k3 O% U<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
0 P1 N$ j4 x; B; p2 E* O# T& p6 I( S1 z, I( H
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-5 16:31 , Processed in 0.097643 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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