飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7982

主题

8070

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26276
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式

: o7 l4 ~% \1 [5 P9 ]" ~<h3 id="一序言">一、序言</h3>! B) K$ }- f& Q& u9 F
<h4 id="一背景内容">(一)背景内容</h4>
0 H* r- `2 X) Q<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
' f4 z' @% l  f0 M- e" X" t; }; Z6 I4 `+ I<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>, X4 A  G/ }5 ^0 B5 S
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>$ j! @4 _, h+ Q% C
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
2 [& E' s$ X" K& l: j<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >0 ]9 E& b/ F: ~! q- l+ A
<h4 id="二场景说明">(二)场景说明</h4>. [% {2 R" x  x6 t1 j
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
4 T6 y. M; I( u- p<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >0 n* }6 h" g' C+ h, M1 u5 e
<h4 id="三前期准备">(三)前期准备</h4>
( A; x, R/ R% V* z- H<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
2 x, b, C+ @/ K) j<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >3 H, b# _  \! W- H1 F( n
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>1 `! `, K* K$ U0 F
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p># {! f# s/ M, A* e" e0 Z% V
<h3 id="二一对一查询">二、一对一查询</h3>
* V. T* q) ^' s$ o" P<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>9 L. x' ^, \  ^& L
<h4 id="一查询单条记录">(一)查询单条记录</h4>
3 Y2 ^) U: C5 A  S  a<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>/ U7 G, T5 w; ]" R7 T
<h5 id="1示例代码">1、示例代码</h5>2 u% I! u! J, P5 W9 H9 ]
<pre><code class="language-java">/**+ ]" @/ R, W- {. w8 I
* 查询单个学生信息(一个学生对应一个部门)- M! j, E8 }8 K3 t7 B4 Y
*/
2 N$ }7 |4 y4 h- |. r2 n+ _public UserVo getOneUser(Integer userId) {
- e1 g9 ~" r8 h; ~3 W    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
# V, d0 Z& E: u        .eq(User::getUserId, userId);7 l) k8 l  ?$ Y7 H  z5 ^
    // 先查询用户信息' o+ J- e4 B( X8 ?- N% ^
    User user = userMapper.selectOne(wrapper);
8 i/ l8 u- l1 U6 P    // 转化为Vo
6 \4 K, Z6 s7 Z$ F% M    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);( h% d- `8 }" B, f" f/ c
    // 从其它表查询信息再封装到Vo$ O7 _/ G$ [! r3 @0 U' D9 h5 n
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);# C% j+ `  ^/ V0 _3 z7 ]" k  T
    return userVo;. H& X! @# e0 M; g. p% Y/ A2 ^- w
}$ S) `* m$ P% N2 X
</code></pre>$ z1 ?4 u' t' Y# |
<p>附属表信息补充</p>  S* M8 p( S( F7 I+ J# G' `
<pre><code class="language-java">/**" H4 O5 c# F2 }% l
* 补充部门名称信息
3 l& \# l8 D) [0 A */
- C; s! s$ I  [) |8 c4 ?private void addDetpNameInfo(UserVo userVo) {# z# c' v; j/ z- F# {! ]8 [$ A
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)' Q) S/ ~, s/ N& M" x  M! G
        .eq(Dept::getDeptId, userVo.getDeptId());" ?+ `3 q8 z/ o! {. m- Z# _1 z
    Dept dept = deptMapper.selectOne(wrapper);
% q+ l: T- y7 p+ O    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
/ Y# x# F' k  E5 M  c. x# ~3 {+ C}4 S" J. [) E. s& Y& e3 G
</code></pre>- [' A5 Q. H6 y- w- I: y$ g3 F7 ?
<h5 id="2理论分析">2、理论分析</h5>
" U1 l& }7 i5 f; ?<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>% {% T+ ?0 \! |0 N3 I( H
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
% t4 W  w' f( Z  t<h4 id="二查询多条记录">(二)查询多条记录</h4>
5 X+ E. I2 \7 R% K<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>. a+ r3 B8 F% J  ^. F, q
<h5 id="1示例代码-1">1、示例代码</h5>. m3 Z7 E; }$ @
<pre><code class="language-java">/**
( D% s& U  N) g# L- ? * 批量查询学生信息(一个学生对应一个部门)
! ?9 Q. a; S: @5 X% S */- g- h# @/ f% a* D
public List&lt;UserVo&gt; getUserByList() {$ I- a/ ~( h0 D, R
    // 先查询用户信息(表现形式为列表)8 I* E- u& L. W; A
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
8 J9 ]/ J' {8 Z, l2 x) Z    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
# W# ]; P" _* `- \* e    // 此步骤可以有多个1 y2 x7 N. q  o# h3 q0 v
    addDeptNameInfo(userVos);9 _1 F3 W1 l8 B
    return userVos;7 H9 L4 t1 B5 r$ i
}% u) j9 e* `4 V9 B
</code></pre>  ?* T8 d+ n  w, Y
<p>附属信息补充</p>& O* g& U9 c, _* z1 v
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {0 Q; U- d$ P9 E4 l, ^5 }
    // 提取用户userId,方便批量查询: ^) j4 q( V- z
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
( G, ^5 Q1 ^8 e4 W/ R( E    // 根据deptId查询deptName(查询前,先做非空判断)
. @3 H8 a" L3 A; D    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
) S7 R4 _. G, R# Z) n' m9 w6 L    // 构造映射关系,方便匹配deptId与deptName
! w4 a  _+ |0 A/ P    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));, O) T1 @0 q* ^& f# ?
    // 封装Vo,并添加到集合中(关键内容)
4 N! d3 u" ^; O! P, y) I4 C4 c    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
1 [! i3 ^' F+ @7 X2 s  t: P}( C9 l, `+ E4 ^$ M" f2 C
</code></pre>
7 d, d; |: ^! h" i! V, s0 p<h5 id="2理论分析-1">2、理论分析</h5>
( s3 {+ h& h+ `; m; F: S/ k<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>$ X8 u1 x( V( _% r
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>( ~- @( ?# K) H! X
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
0 w8 D$ Y0 F) G7 Q# j/ b$ A<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
/ G) w$ v6 g8 ^4 L<h5 id="1示例代码-2">1、示例代码</h5>4 H0 a+ y* U% ~& Z' u" ^
<pre><code class="language-java">/**" V- }0 v6 u) y
* 分页查询学生信息(一个学生对应一个部门)
' k7 z0 Q3 B& S/ f */
6 u! J0 }& i% u+ k2 Rpublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
8 `4 o8 s# x7 h' l    // 先查询用户信息5 }, {8 i5 `9 i- f: D3 K
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());0 u+ L: W$ a  v
    // 初始化Vo8 _0 N5 [* Y' J& N1 L9 q
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
9 G- u# B  {$ f# E9 s    if (userVoPage.getRecords().size() &gt; 0) {
/ q, P' |  |9 H* _, `        addDeptNameInfo(userVoPage);: x) C7 h& E8 Z3 c: K
    }
8 O* |4 O* S7 r    return userVoPage;, I) z- U5 G, U" B! g. O: U7 @% p0 ]
}* ^9 H9 b! N! N- m9 x
</code></pre>
4 ~4 F& Z3 s8 b% q4 R! M<p>查询补充信息</p>5 O/ l% ?' W/ L) i  Z* L$ v, t
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
2 p% V( B) f6 }  G$ N    // 提取用户userId,方便批量查询
* |4 `1 K2 U  u    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());/ |( R+ g+ Y5 a1 \
    // 根据deptId查询deptName8 Y" J: w- z% O  d$ L3 Q# y& Q
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));- t  p' f# y5 l+ Z, s7 [- i! f5 {
    // 构造映射关系,方便匹配deptId与deptName  c' g3 x! l, S
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
* ?; V2 t" N9 ?/ M% W6 [: M    // 将查询补充的信息添加到Vo中
* e; s0 E( Z  S; Q' v5 o- @4 l0 S    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
1 q2 w: P, S1 w! ~2 Y4 P. F}6 ]4 @! g# l$ E0 Z% B3 g/ E) a
</code></pre>5 f. E& o# X! W
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
" |0 `7 P% s* |<h5 id="2理论分析-2">2、理论分析</h5>4 E# j! x4 n/ q0 Y9 K3 ?
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
- Z3 ~7 s& @" d4 x# v( h<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
: l4 u% C% Q* B+ ^, z$ O0 v<h3 id="三一对多查询">三、一对多查询</h3>
4 L: K; i% W# X# g5 V% y<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>- u; Z' \" C/ b4 Q
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>  B( g( S$ |2 U5 `
<h5 id="1示例代码-3">1、示例代码</h5>
( V7 i& ^& O% ?<pre><code class="language-java">/**
, C% L# L- t) i" |- ? * 查询单个部门(其中一个部门有多个用户)
2 t6 {8 P2 L* p4 V6 ~1 k: _ */% q" l! F5 s5 i: ~$ f
public DeptVo getOneDept(Integer deptId) {( `  y2 c7 P5 a) R( z7 A
    // 查询部门基础信息+ f% m! V6 E& m
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
/ U- O' Y2 N4 p# o% p    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
0 Z: O2 Z, O# C, R2 d7 H    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);5 E# Z4 W1 H6 ?* b- X
    return deptVo;- ~* W. E; q. n% u# v5 `# u. j% r
}
7 t! O, ?) s. T0 C. S* f6 j</code></pre>
) @1 I' a! t& e- ]8 X: V<p>补充附加信息</p>
0 W. x$ Y$ y4 Z% F& _- v) d4 ?<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {6 Q- ?, {& j# Z3 ~: ~: Z7 G
    // 根据部门deptId查询学生列表) j. q! P& l- T' Q/ x
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
; Z. X0 f' V. V  ~, e  V% y    List&lt;User&gt; users = userMapper.selectList(wrapper);
7 Z# ~2 H" {$ M/ j1 x# t    deptVo.setUsers(users);
& f" \" z& }. P' ]}
6 Z) A1 w3 b+ _, H2 m</code></pre>
2 l" ^: Z1 J2 P2 i5 K<h5 id="2理论分析-3">2、理论分析</h5>
- |, ]* v5 a$ n4 ?6 O6 \& {5 g<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
" d0 |4 e* C4 V; v0 I# k<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
7 u" a7 ^. R' e. Y" o# F( C) f' l<h4 id="二查询多条记录-1">(二)查询多条记录</h4>% ~* k4 Y3 [1 D
<h5 id="1示例代码-4">1、示例代码</h5>! B" |9 }6 i2 w
<pre><code class="language-java">/**
" B/ d' Y4 }% a- b  w, R+ A% X! l * 查询多个部门(其中一个部门有多个用户)
7 u- P( X; y+ E3 U7 j" o) c! l7 a */
/ q, X: |7 K1 I0 B: B1 f5 kpublic List&lt;DeptVo&gt; getDeptByList() {- i0 P7 e6 ^0 W: `( z- \
    // 按条件查询部门信息
6 ]! B; ~* l8 a* @! I7 M. L& p    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());* o3 H) e% Z, a% g" t/ I$ j. C
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
- I/ C) V4 a! j. G0 W  o5 z" B1 A    if (deptVos.size() &gt; 0) {
, J+ `4 K/ B& `2 A+ ?' o7 G        addUserInfo(deptVos);
2 |  b- ]  z8 z    }: }; F8 h5 \" b1 a7 W
    return deptVos;
1 |# M7 E5 C3 H2 L}
2 Q7 t3 M, i$ Y: p</code></pre>/ D8 J# ?5 ^" d. w2 i2 H
<p>补充附加信息</p>
& c' Z9 \3 {  ]6 Q9 R0 G<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {2 l& x- J, c' B
    // 准备deptId方便批量查询用户信息
1 ~" M: Q( _6 B+ ]2 Q    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());; f# l% Q* }5 k! u+ m+ G7 V' t
    // 用批量deptId查询用户信息: ?2 q6 |+ ?% @
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));" y% a* ]1 d9 s* w- k7 r4 V
    // 重点:将用户按照deptId分组0 I0 \: x+ ~# S& m0 B) H
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));( r1 b& K& I' p% V# V% S( V! p& E) W4 ~% n
    // 合并结果,构造Vo,添加集合列表
/ K, z8 _7 J, g1 U9 v0 F5 d0 g; n    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));0 h$ B5 `# {- Z5 N
}5 Y& P$ a# I7 M$ R3 ]4 e. |) o
</code></pre>$ _, y3 O# }* @, [. J
<h5 id="2理论分析-4">2、理论分析</h5>" \: V/ `1 A# O9 F9 x
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>8 I! Z% u1 c& V, V! `1 X1 G+ b1 _
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>& A+ `% O8 _( J; M
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>6 x5 q! @( x0 S  x* M9 [* u
<h5 id="1示例代码-5">1、示例代码</h5>; F7 P1 r! }" ~( K4 d# h$ E
<pre><code class="language-java">/**
) U2 Q& r3 r, a( I# ^ * 分页查询部门信息(其中一个部门有多个用户)
" q* g9 u. ?# E- E: E+ Q0 [& | */
0 d, q/ R2 p. E; P* ipublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {% \8 `/ ]3 \7 y+ t( P+ ?  }
    // 按条件查询部门信息
" O# b/ m5 r* v8 P    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
; W, m8 e' \# Q- d4 L" e. Z8 c- `    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);9 G' G0 z9 V7 d2 a% h% J6 Z
    if (deptVoPage.getRecords().size() &gt; 0) {  w# ~# N3 ?! Y' c6 v
        addUserInfo(deptVoPage);
1 M( B  Z4 j; x    }, j5 {3 x! Y: U& O6 h2 k. {& X
    return deptVoPage;0 x" D; E" w: b) K8 l$ M8 n% |  q+ h! f
}7 M$ H( Z7 b3 t. r9 p* T! J
</code></pre>9 j4 A9 s' Y! t6 {0 l% g
<p>查询补充信息</p>  c+ U& v  L9 \
<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {+ Q( w! A" N: C/ o# ~
    // 准备deptId方便批量查询用户信息6 q% a1 y' B* z! m" w! ^/ N
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
7 u* {  u" N0 g# e9 j* c    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);9 S% A' k8 J+ Y: G& M
    // 用批量deptId查询用户信息; J( M% Q1 X( ~2 G+ A" l
    List&lt;User&gt; users = userMapper.selectList(wrapper);6 l/ o8 E% |7 P( O  j/ K$ V
    // 重点:将用户按照deptId分组
0 R) _, T9 [+ g$ ]+ a    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));3 H$ X8 F/ w" H7 D
    // 合并结果,构造Vo,添加集合列表: |9 z+ l! x1 h4 A
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
) t& Q' k9 o) M+ F. u}% Q2 A1 S, F8 U; S
</code></pre>: |, ?& o! L, l% o/ ^4 G7 a
<h5 id="2理论分析-5">2、理论分析</h5>$ \1 f( m, U4 ]& D/ e9 _
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>( ~; k; m6 j  j' P, a5 V
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
! _" p% _0 @6 y( u1 a+ w, ]<h3 id="四多对多查询">四、多对多查询</h3>3 Y) b' S: i" z
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
) ^# f% X+ ?  }# ]" C<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>2 S# K) y3 w. K$ m
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
: ^6 i' E. [& Q, O0 h$ `7 q# e5 [: p<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >" |' r+ Q1 D: S! ]
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>  Y. ^( l: Q7 u, h
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>. t4 q- g0 y& O" w6 i
<h5 id="1示例代码-6">1、示例代码</h5>2 W4 U) P: k$ Z1 ~. Y
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {  ]: r: d+ K; y2 P
    // 通过主键查询学生信息
0 S4 C2 u2 K# u+ U- d/ {* R" `, C    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
6 y' k: [/ e4 T  }  H) K$ }    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
4 |5 \' e" E5 B# ^1 T% L0 R    // 查询匹配关系; i, U) O( E( l% e7 g
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
1 j5 d* U! B* @$ v! v& _  Y0 Q    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());: L' ^1 M; x& d8 e8 t, \6 Q& _
    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {0 p/ D; F) x: D# s7 o) k& F: G* P
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
' y6 k- q" ^3 a6 {        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
( Y+ _, F: s/ A# z7 h        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
, y# v- v5 `% @8 C* d8 k6 _9 J, Q" j        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));$ G9 X2 B$ y0 m# N7 ?8 [
        studentVo.setSubList(subBoList);+ y0 ^8 Q' X; ^# B1 K" I
    }* `+ a2 z* S5 A' c4 Q* b/ Q2 Z
    return studentVo;
$ C3 u  S' n. f- l; u6 {6 |}
  A4 b9 M) R8 b- a+ P3 f7 E, j' i! k</code></pre># X/ B, M" \. Y
<h5 id="2理论分析-6">2、理论分析</h5>& o# P" J1 Q% y0 @4 C
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>' F/ C- H& o2 F2 f, F9 }( d
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
, o2 u5 I- P3 n. g/ O" c1 f# {$ a9 g<h5 id="1示例代码-7">1、示例代码</h5>
3 X& q. h& x3 Y4 e<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {8 K& @0 d0 r: r$ k
    // 通过主键查询学生信息
, g" X. g, [/ _3 e8 k    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);/ l4 R; l" z( t& @( A
    // 批量查询学生ID
9 S: n2 O; @7 U3 G  l  R    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());  d4 G& N. Q  |6 H  o, l7 H& ^7 A
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
! C& C6 ^0 D  G6 C4 \, {    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
9 u+ B6 E8 E4 t) q2 T! Z. \& u7 i    // 批量查询课程ID
" U" w8 v3 I7 E& a8 v' L: B: q3 _    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
- P) H$ E- L3 d( P    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
, B" T1 Q1 P& l' c; S, V' Q! R) g        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);- |0 y# l2 O7 Q. V; k, a4 B, w3 n
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));2 u3 u. l# \' {6 V  @9 B1 v. D: N3 w
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);7 I: g: u5 S$ B  s
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));8 n9 O7 S( a" j4 l& q" H" v
        for (StudentVo studentVo : studentVoList) {9 ~9 t* I# p, n8 i- F1 i7 W
            // 获取课程列表
' Q8 {+ W; Z* j, W2 L$ S  i) H1 E            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));8 t* F6 C' x1 x- |$ ]4 @
            // 填充分数8 M, o) |# e. u4 R8 O( e/ T# g
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));& D! m9 \% [+ b+ u
            studentVo.setSubList(list);& \/ U1 T/ W; r1 X' Q
        }
( |* B. s  b2 |+ g; V    }
2 z8 N. I: e+ [8 i0 M    return studentVoList;( x/ o9 w! ?4 M" h) h5 v! j
}
9 @1 Y) @. y& K! [1 z" @/ C</code></pre>
" c; g$ ?* r/ v6 W% |: n4 Q<h5 id="2理论分析-7">2、理论分析</h5>
% m5 V5 G/ W6 H  F<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>: N  E) o" k+ x' t' R8 F% q/ q
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
* t6 h- t% F6 u( b<h5 id="1示例代码-8">1、示例代码</h5>
! }( I9 J3 J3 t) b- V<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {' E, ^7 }+ h( k3 i5 F  c  t4 }
    // 通过主键查询学生信息; i6 q$ v4 w* _, j, c4 P
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
- D( Q: T& V0 K/ `% [3 O* H# r  G& e    // 批量查询学生ID5 i7 X4 Y5 u7 p9 b% x" i9 X! X
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
. j, @# Z& D! F7 g4 h$ g' h    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);$ @1 F$ B) k4 |+ N3 c
    // 通过学生ID查询课程分数
5 e6 C. @  Y" u" _( q% d! S    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);% u2 q2 ]2 P& u4 O' l* D9 D' w- x, h
    // 批量查询课程ID
# b' E" [/ P1 S3 ^- p. }& H    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
+ ]# y3 m' z6 C/ |( K    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
3 C& L2 U% J4 _4 [' L/ r. U' t- {        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);' Z- ^9 P7 B% C+ X
        // 学生ID查询课程ID组# a$ Q8 g6 z$ s
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));# J" Q# e; i1 q) u7 `
7 E" E1 |' t* z
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
9 t; A, E1 W: n        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);# K0 w5 V- }3 I0 M
        for (StudentVo studentVo : studentVoPage.getRecords()) {
6 R$ |  w9 k: \- g            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));: U& X$ H' ~+ Q2 F
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));9 Y* n* L1 K9 J9 y; w
            studentVo.setSubList(list);
* l3 O" P( Q- ~: s5 Y9 r3 ]& Y8 u        }; d+ G5 r; z1 F! z2 l- b/ ~2 \, N
    }* }6 ?$ X" _- g9 H5 q9 R' g( l
    return studentVoPage;
4 K& v( f9 b" ?) |) I}
' z* R/ `7 J9 B3 O  |6 X</code></pre>  R, c- }. M  M2 I( S
<h5 id="2理论分析-8">2、理论分析</h5>8 r& p* `0 [$ N) j' v% G
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
4 |* O5 r+ G! u* C<h3 id="五总结与拓展">五、总结与拓展</h3>
& H. D1 P1 z& `* K<h4 id="一总结">(一)总结</h4>. l: s! J1 @7 @4 n* E+ R; i: ]
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
5 l2 \( H0 V5 Z/ a* E+ Q" W<ul>
- W! b. ~0 X$ G3 q7 @<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
, z5 d4 z3 S5 I. }2 k+ U7 ?; k<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
/ A: t( f- W' F8 {<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
. S4 t! y1 _2 x8 h</ul>
7 J8 L8 b$ u9 J5 e( N8 H- Q<h4 id="二拓展">(二)拓展</h4>. x' @3 ~( R5 ]: R
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
/ q% X6 C6 W5 B8 h' x/ F7 T<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>8 H  p/ x4 j% c3 S- |( q' X. g3 a
<ul>' Y7 n% |/ X* p/ I2 v% R
<li>当数据量较大时,仍然具有稳定的查询效率</li>' i" K( k  l/ z# h8 t! e/ C  r
</ul>
9 M1 ~% s1 \" O! |0 e<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>2 P2 j6 M$ J0 b- m3 ^1 k
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
6 i& G" Y% U8 g9 F; d$ ?7 X<ul>* f' T  s! y5 V! ~( E' |0 r
<li>与二级缓存配合使用进一步提高查询效率</li>* o, w( I* m8 ^5 S
</ul>
. C2 I- F  w0 ]2 h<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>9 n' G! D" \) v9 m, {7 u
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
; H  c  ~8 X  `& P5 G' _3 W4 z
$ R, c' P6 x3 m' c" ~
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-11-27 05:23 , Processed in 0.079029 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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