飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8032

主题

8120

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26426
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
+ z) y7 B4 D2 j4 ^& O" F
<h3 id="一序言">一、序言</h3>) y: ~; a7 p7 Z' E2 _
<h4 id="一背景内容">(一)背景内容</h4>3 W; o( Z% w6 J
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
% R& ?! L7 J# E  a# J# b3 `1 ^<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>8 Z2 t: m: `' G& O0 p7 t
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>- s. H8 q% e' o8 F
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
/ ~1 V9 G0 s) P2 r4 f0 t<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >+ G+ u4 h- r1 N2 Y
<h4 id="二场景说明">(二)场景说明</h4>
5 }6 K, @% Z  j9 e6 s+ O2 I0 \1 s<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
* Z4 _# m  [5 a, b* i  X* e<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >9 {& D1 c: h4 k. ^% b! k) |
<h4 id="三前期准备">(三)前期准备</h4>
) o  m$ {; H% |# O. V<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>5 t$ @. j$ n; b
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >, M$ J+ n/ T  E; r- v5 V* _
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
0 N% B: B" G$ Q2 b( d3 M. W<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>, M- r0 d6 u6 l  B
<h3 id="二一对一查询">二、一对一查询</h3>) b5 n0 C5 B) b% ]/ A9 E
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
( @# e+ J, Y0 P( v3 l% \<h4 id="一查询单条记录">(一)查询单条记录</h4>% X- ?- n# O+ v" q" K
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
  G" T# C- X- o* @# e<h5 id="1示例代码">1、示例代码</h5>! F4 J" k/ J5 A( K0 G0 N! t
<pre><code class="language-java">/**
) f% r: j1 H; x- M# r * 查询单个学生信息(一个学生对应一个部门)- Q6 \& H" H" G
*/& Y! Q5 W+ g. _; s' c
public UserVo getOneUser(Integer userId) {
9 S" J$ n# c) U, _* E% U, c% K    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
0 |8 e( \; a& R        .eq(User::getUserId, userId);
- n. ~' Z  L- d    // 先查询用户信息  P. `' t# Y# b$ H6 a7 N1 Y
    User user = userMapper.selectOne(wrapper);
: B7 i0 F6 S/ Q$ T3 \/ X1 [2 }- t% ?8 d    // 转化为Vo
+ T+ J1 {1 ~6 B! F# U' I) Z: |    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);  q+ z" s& |3 G8 Q0 v, [3 F0 ^3 F7 G& p
    // 从其它表查询信息再封装到Vo
3 U4 I; b" q8 S3 F    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
: j( U: ?" S$ d4 Y    return userVo;
0 V  e& v3 k* ?: j7 _+ C; |" \}
3 j- m, a# E& J; B6 O3 R, a* A</code></pre>' K1 v6 W9 ]  H2 m
<p>附属表信息补充</p>. F" {0 v- J7 }9 \
<pre><code class="language-java">/**
! m' i6 v; X! I2 p7 y * 补充部门名称信息
- U- L; L0 L% l$ ~8 ~ */
9 d' g# H, f' Pprivate void addDetpNameInfo(UserVo userVo) {
1 b+ a5 K, ]* }% m    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)5 J$ k3 G! x' S1 J2 C4 I* x3 p, P8 m
        .eq(Dept::getDeptId, userVo.getDeptId());9 H( X! q/ c  N/ ?% \
    Dept dept = deptMapper.selectOne(wrapper);
& l  ~1 n4 c5 x8 R& I/ S! I- U' G) [    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));5 O- S7 `3 v+ X
}
6 ]2 @5 z7 ^9 D( j</code></pre>2 n" j3 V; j/ P, z( |0 s. ^! @
<h5 id="2理论分析">2、理论分析</h5>% J1 A/ t4 b$ ^% b. {& b1 F8 ]( {
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
% g  {8 H1 R# P* N" E0 d<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
2 h; e4 l$ w% k; k  @<h4 id="二查询多条记录">(二)查询多条记录</h4>
! E2 h1 I; @: t4 R$ j<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
+ P  x) V! t3 |* ?<h5 id="1示例代码-1">1、示例代码</h5>- C9 R/ p+ |5 _# ?8 w
<pre><code class="language-java">/**
% L: r. s7 T5 i! O: p * 批量查询学生信息(一个学生对应一个部门)
" d+ F' G, U9 Q3 w% }6 o" V */+ S- J9 a! g% h$ k
public List&lt;UserVo&gt; getUserByList() {
' P: q$ X' p' x, k' _    // 先查询用户信息(表现形式为列表)
- {0 F# E5 F! ~  t# |9 E$ ]    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());1 R- P, v! U0 d* l& m
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
- U3 a8 \& m& T( m) r! [; m    // 此步骤可以有多个
. {5 g& [# E* _( n    addDeptNameInfo(userVos);, d1 v5 R* A7 P0 \3 Y
    return userVos;) T) W: l& w! ~* `+ [) H
}% b1 F4 C* k, ]+ y$ Q% N
</code></pre>& ]# a7 U+ M' P: B$ Z- |& ]4 p* h
<p>附属信息补充</p>8 L' ?' `+ P# L" P
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {
3 i9 ^  z3 F2 J    // 提取用户userId,方便批量查询2 C2 e" y# L) u# u$ S( A' J
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
3 ]. K/ y9 s7 q3 j, G# m' D! I$ E    // 根据deptId查询deptName(查询前,先做非空判断)
' r6 R& b2 c3 q, \/ b, d    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
# S# n( u9 Z- D& k* k    // 构造映射关系,方便匹配deptId与deptName) r. u. V, o) a5 J
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));" Q! w% |' G0 Z! e* Z( J. U- q
    // 封装Vo,并添加到集合中(关键内容)- J1 S, U. R) I8 `) F
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
8 @+ \: S* s$ {3 j6 [7 \}1 t3 ^- {9 L' f: q- }
</code></pre>
" k. S+ A& ~, g( ?# z( I( g& Q<h5 id="2理论分析-1">2、理论分析</h5>
8 E/ H3 e; E" c9 ]3 m! [$ e<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
; M. ~9 Z) g6 C$ K& i* T<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
. d" i; c# A0 |: t  `. b  N<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
' r- F* w! d! N6 R( ?2 K<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>- T# g$ M) P: T
<h5 id="1示例代码-2">1、示例代码</h5>
/ n2 W2 G3 M' [& m; I<pre><code class="language-java">/**
- P3 k; M1 [0 _+ l) s- h+ { * 分页查询学生信息(一个学生对应一个部门)
3 S4 {' _$ Q+ c6 ^- d( }" k. u! h& ^ */- b( D$ r. [+ i. ]) y
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {# H) k5 Z1 X6 E$ A, D
    // 先查询用户信息
% t3 w- h& h( U7 V  E0 ]! d7 t    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());0 x3 o. o! q$ o
    // 初始化Vo
; c9 H( B- F/ Y% y; b4 S1 S    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);5 s- |4 r! S2 t& S1 j; b$ ]# I
    if (userVoPage.getRecords().size() &gt; 0) {" F; D6 r% l; `0 q- F& h' S
        addDeptNameInfo(userVoPage);! Y$ P' y$ H; b/ z3 s! \
    }
% l  u6 v9 q3 w( j    return userVoPage;
2 p: F5 }8 P4 L, T4 k}3 C. P  C: L' Q/ O, ?' H
</code></pre>
2 G3 a8 [8 F$ W8 [# E<p>查询补充信息</p>/ M# U3 z) ~1 ]! G/ I, I
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
( X: x9 {7 ^9 h4 u7 k0 t5 v5 }. t    // 提取用户userId,方便批量查询* O8 U% x6 R- q' A9 k+ {: h
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());: }1 Q8 V" l. h
    // 根据deptId查询deptName$ m: w  E. s" r
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
* p! b, e" p4 I) Q1 P, [& j# e    // 构造映射关系,方便匹配deptId与deptName
% e5 ?( @9 P2 K    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
2 @0 @0 m! G$ ^% E. U    // 将查询补充的信息添加到Vo中
/ S% k9 G/ _0 G# {) m# ]  C    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
5 o+ p& i$ `3 x2 F- Q* S}
9 f! ^# P' ]9 I8 u: o</code></pre>
' L: [0 m& u: R<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>1 |# t0 }! t) U$ E# S# w# ~$ E
<h5 id="2理论分析-2">2、理论分析</h5>
* A* l& G) h' g  t6 A5 ^<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>0 i9 ]0 Y  ?0 ~# w1 B
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
. c+ n7 ?, ^5 B9 z9 [% b+ W<h3 id="三一对多查询">三、一对多查询</h3>/ F' @$ j/ S  `" l5 W' b
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
" n; y) {+ ^* h% g7 ]<h4 id="一查询单条记录-1">(一)查询单条记录</h4>( y7 a4 L/ i" B: k
<h5 id="1示例代码-3">1、示例代码</h5>2 v% y  h  o5 ]
<pre><code class="language-java">/**
; M* F) d: r. E1 }% E: J9 D * 查询单个部门(其中一个部门有多个用户)& U$ ]( b. V) m: K$ O# [# h
*/# F( S" X  R1 E# S; ?
public DeptVo getOneDept(Integer deptId) {
$ |, N2 U# K. \    // 查询部门基础信息4 d; v+ M1 ]8 ?7 S! j2 n
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);# e+ A9 k" b2 s# \- ?
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
7 d2 ~+ n; O+ S8 |: U% `( D    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
6 w/ L, Z/ X- H8 u5 ]    return deptVo;
" ]7 L" \. t. L6 r}
  v) A% N/ [8 b9 E5 C</code></pre>( ~0 ^. E7 D1 M! [4 V5 V# p) h0 Z
<p>补充附加信息</p>
- W% R6 R9 N2 t+ N! Y& i7 [<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {- _0 q7 @" ^4 \2 s
    // 根据部门deptId查询学生列表
; u/ R4 n. {6 Q( P  E( C    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
, H  V: Z& o, O    List&lt;User&gt; users = userMapper.selectList(wrapper);# Y3 ]3 u" G2 W
    deptVo.setUsers(users);
+ d$ e7 N/ x5 j* c}
4 Z( B8 \) C1 Q6 v</code></pre>
% _0 ]3 }" u1 M9 a0 y$ p3 v8 V<h5 id="2理论分析-3">2、理论分析</h5>
: ^8 U: c5 G$ p% v( G; @<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>. S- `! A/ l- e; B- u
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>9 F- ~, W6 F2 @- I& k. W
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>; z6 A4 {. ]2 a( X2 l$ c' [
<h5 id="1示例代码-4">1、示例代码</h5>/ H/ S- T2 j* j; s
<pre><code class="language-java">/**/ y: C: s, W, }: |0 w6 \0 V& ~7 Z
* 查询多个部门(其中一个部门有多个用户)
- M+ l/ a  ?- \4 p8 C$ b; S */: i+ }# N. h$ J, O3 U5 n6 t
public List&lt;DeptVo&gt; getDeptByList() {
9 b/ ~9 m6 ?5 {1 N. L5 V    // 按条件查询部门信息% ~+ _. {$ f0 H7 Z* E5 c4 {$ C" {
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());5 i' |( T0 t' Y2 s  ?$ V0 Q5 K
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
" @! r, Y. H4 a! o' F    if (deptVos.size() &gt; 0) {
* @0 \  }% E- G1 d+ _5 W        addUserInfo(deptVos);( N& q' t" ~( T5 k( h
    }
- ?4 d5 h3 a/ p+ Q# b% S" Y# j    return deptVos;
& V, g5 k0 W# m% ~}
  V' v& E: e* |7 _3 |7 s</code></pre>/ Z% A) x( k7 d# ?$ m$ u3 `
<p>补充附加信息</p>2 W0 n! s5 F( B- F8 u
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
. d# a* A* L" H+ T  E( d    // 准备deptId方便批量查询用户信息
9 `  a$ G+ }* `- {) \, f/ _2 k+ l( ]    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
: S0 M, q# c- q" m) T$ f% D7 }    // 用批量deptId查询用户信息
' A( |' }0 ?- G7 N    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));0 Z8 g& l3 X  e
    // 重点:将用户按照deptId分组- R0 k9 [. n2 x  H+ N  Q& l- A; g
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));6 u. O4 r; y; m% D
    // 合并结果,构造Vo,添加集合列表
0 _- P. _" W. C  E    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));( d. U5 Q% M. X# M
}
9 I4 r% X: v$ t6 L# F+ c( K2 ?! ?" ~</code></pre>
/ \( N* ]6 w/ Y8 G# J<h5 id="2理论分析-4">2、理论分析</h5>7 Y) q6 r% h; k- I" Z/ C+ X( |
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>1 F6 n+ Y# H7 x/ ]
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
: t9 Q7 a9 Y  J( w5 I<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>1 H5 Q7 |9 e; m- R; t3 v2 q0 l
<h5 id="1示例代码-5">1、示例代码</h5>! a: T, u8 L. c
<pre><code class="language-java">/**$ Z' W* X# N& c( K# p8 P' v/ h5 |
* 分页查询部门信息(其中一个部门有多个用户)
+ |' G( f/ B( `2 a */
  [5 E8 t; K: Y. r: _public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {5 \0 ~6 t; E8 `7 i* E0 J6 o; A
    // 按条件查询部门信息
1 z* e* @- O) J- x    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());1 }# p! I2 M* G- U, D
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);# x- \4 q, {; H/ T( B! z
    if (deptVoPage.getRecords().size() &gt; 0) {
. u, {9 S( `) O: ^; ?& z        addUserInfo(deptVoPage);3 L, F( M0 [0 m; B' l
    }
) q, b( u3 l/ K7 J/ W    return deptVoPage;
" k( G7 A2 `! `$ |  G& k# k}
7 `; x6 {$ S% K- A9 U2 y</code></pre>
9 V# s8 d' R$ L; `; E<p>查询补充信息</p>
5 f- X: t; b! N8 a<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
9 H. [' T- r4 ~6 M    // 准备deptId方便批量查询用户信息
& t* P* L" o  E    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());: @* z$ h1 m# {& W5 s1 U; T
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
* m3 u8 o; Q" L* F( |4 s  q; c) ]+ `" e- G    // 用批量deptId查询用户信息" [; A: t+ w* Y& \
    List&lt;User&gt; users = userMapper.selectList(wrapper);4 Z: g& w+ A" h3 v7 y
    // 重点:将用户按照deptId分组
, f' R$ \; k9 B( z. ?    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));6 D, o6 L8 Z& }- o
    // 合并结果,构造Vo,添加集合列表6 `% a- i6 k1 ?3 ]: ]. `# G% k; G8 L
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
% D1 R2 {) e% K" n, O9 P& L}
: l9 l6 K4 R, q' k7 m</code></pre>
; o# H4 f; N/ g" f<h5 id="2理论分析-5">2、理论分析</h5>
& i- v- \6 ], u" x<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
3 h" G/ `6 t. ~7 d6 f( ]( k<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
8 }# G0 p3 \  ^: R, d+ t4 q. W- y<h3 id="四多对多查询">四、多对多查询</h3>. D  x7 r' {2 F/ J3 D
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>$ F/ m) `' x! s0 a/ K
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>5 t' C' o, f; S( K6 G, e7 y
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>- R! z; l2 Q9 r) m
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >) B7 u8 f1 V  j9 l, |# m8 B+ G
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>* p% v6 m8 g- S9 \; U
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
6 R1 r9 m- A3 o! V0 Q$ X' i<h5 id="1示例代码-6">1、示例代码</h5>
9 D3 n5 l" Y% t* I) d" U<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
+ P4 e% ^- g. F1 Y' l  |& H    // 通过主键查询学生信息
9 g1 L! ^6 ]. X* X# f# g- q    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
% m5 N8 m7 m9 C$ U/ P    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);8 _0 H/ c8 k3 M" p) c1 i, O
    // 查询匹配关系
# D8 X+ R6 J5 A- x# |3 O    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);/ e- X9 H+ c# {9 v6 t  S. B. k
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
4 j9 z2 w9 ]5 @3 W. v2 n+ s9 r2 a    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {3 h7 G% `: f4 K- C
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));1 ^, N7 Q$ i$ v* Y+ B$ ?" S
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
+ X4 \8 Z8 W1 h3 D- H9 b/ P4 I        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
8 }+ ?; c, Y0 X) n4 ]8 J% }" b        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));9 b: T6 |6 _. U1 Q3 f; G
        studentVo.setSubList(subBoList);
7 l9 z1 `  g3 _% o4 z3 c8 o    }( P6 z2 r( C# f: {: |
    return studentVo;
8 k, A) A5 y& Q9 y$ j( v$ l}& w8 h: j% `7 t. [( H0 M' g
</code></pre>
/ m  _6 A0 R' n. q% g<h5 id="2理论分析-6">2、理论分析</h5>
4 P, f1 l! N$ J  f5 Z<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>8 Z+ `. V& y8 W  {# |; F, M
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>6 h7 I: F  i4 N- G0 K4 h
<h5 id="1示例代码-7">1、示例代码</h5>/ N- i! U7 \$ f
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
+ ?2 s9 Q, e& j" h  [    // 通过主键查询学生信息
9 T  I# ~  [; `) ]* B    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);& U8 o% x, Q6 l( E  O9 f0 D" J
    // 批量查询学生ID2 U! h' c- O$ O) Y6 e3 I
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());/ v' T1 X0 M- ], \) d& ]7 n$ \
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
& x9 Z) i! E$ X# P    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);& {3 N  s2 h2 r# r; x
    // 批量查询课程ID" x" l, r4 b  z' i: C
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
1 l3 u2 f+ ?  k: z% q* C  {& q) |/ W! `    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {3 A6 W+ v. i, k$ x. M" U9 F- M- C
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);$ ^- h4 w  w% c! I" ~
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
/ P% g8 g9 t2 g9 \* ^! A) W9 u        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);6 P8 {7 u  [" ?6 Q
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));1 K8 a; ^) m5 u# p
        for (StudentVo studentVo : studentVoList) {
( l& }3 j( b$ q/ w+ Y$ s* X  l, c            // 获取课程列表; ]  I& L5 D  ~  Q
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));% @$ |# X8 u! A! ~: j
            // 填充分数" Y$ E8 t: v9 t) h
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));7 {7 C& {$ b8 e% L
            studentVo.setSubList(list);6 P# a3 g. s3 P; e- n8 o4 o
        }: z2 A3 Y+ A" `% S: J7 E
    }2 ^. ^6 N4 i, M  @0 s7 |
    return studentVoList;8 s2 a# ~& k% y* y7 f9 P$ T% Y5 C: c
}
$ }& S$ B0 Z: i3 P9 K</code></pre>
6 o8 ]' P; R. x1 `+ u2 D. D<h5 id="2理论分析-7">2、理论分析</h5>
( D! z1 ~$ [6 t8 j7 t) r1 C8 q<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p># @( b2 i$ d  H0 T& i
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>  t, ^3 G$ ~$ c% ~. g& G/ Y
<h5 id="1示例代码-8">1、示例代码</h5>
) g3 J! ^; S. V5 Q0 T* K. w1 ?; E<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
  D- ?6 v' ^1 R6 S    // 通过主键查询学生信息& ^. S- U9 C# F
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);7 b, e8 D$ V6 H; K2 y
    // 批量查询学生ID
: |& r1 ]; O4 S" S; x& k: d4 w    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());2 g3 B3 b( g+ a9 \
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);9 Q% [4 h8 l  }, z- L9 H3 K' c
    // 通过学生ID查询课程分数
" W# Y4 n  O! ]; _3 R    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);' u3 |1 O# E" _# S0 O& z6 i/ Y
    // 批量查询课程ID3 R- |% q/ i* Q( ]9 O/ t; J6 e
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
2 n# m+ a/ ?. Q/ ~& T    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {2 L# B; z  h9 g5 S9 @% M
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
, d, q: S" i1 c; s) W1 L        // 学生ID查询课程ID组( g' c) i5 A, @4 l# N' R
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));; s% @! B7 W' D8 d5 |% J- s; o8 q

  s' @7 U3 W% N& ~0 r# G" L8 n        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
! q2 ~+ C0 j! H5 G        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);8 ^$ E- Z: W( w, ~2 I& o0 j
        for (StudentVo studentVo : studentVoPage.getRecords()) {8 X9 X! w4 l$ G) W2 S/ A
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
! Z$ w/ `- u5 P, l% ~- {6 \            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
5 L! ^% R4 H5 o" z# x            studentVo.setSubList(list);
) ]; Z8 A5 D3 L) R        }
* \" c# j: \; e, {: x8 X8 j    }
4 n& y6 l& x9 L6 T2 \! E    return studentVoPage;. v6 E3 V4 N. W3 |0 h0 l3 _
}+ G* I: `5 ?+ D8 q
</code></pre>$ `6 Z" s2 M4 P+ o9 J
<h5 id="2理论分析-8">2、理论分析</h5>
6 t6 B% ^- g5 q7 Q. l+ B<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>/ x  D2 t- c% c4 v) L9 a
<h3 id="五总结与拓展">五、总结与拓展</h3>, X" {) D! w: C# C7 `
<h4 id="一总结">(一)总结</h4>% U9 x1 Z! q6 z% `% y
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>! n( l% N9 h# j  z' y
<ul>0 @3 M! f( w$ z3 u+ |& {9 }+ P3 z
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
) l1 T, B) ~5 ~( \' K" h- ?9 v<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>& c6 L; l. w2 K' s+ m
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
9 [! r+ H, S+ s7 z$ Y! ?% J, k</ul>
/ _5 S+ L; `* y<h4 id="二拓展">(二)拓展</h4>
1 c" A- _+ E: [2 W<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
1 ~! `3 H- t5 N5 T( d6 v, T5 Z( V<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
: i3 D1 n/ s- l  q2 l2 ~<ul>
, ?' M1 J! n' P+ F: Z" Z; ?<li>当数据量较大时,仍然具有稳定的查询效率</li>9 d1 E- [0 T" z& Y7 m1 Q
</ul>
+ A# u. j) P0 @$ a<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>$ b2 e- ]' H  n) I* L
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
1 N+ M9 d% A2 {: R  H<ul>6 _4 o6 |$ w5 |. t
<li>与二级缓存配合使用进一步提高查询效率</li>
6 Q& M: b# |0 _2 F& u# W</ul>
8 b7 |7 r- ?/ \0 P+ Z7 E6 B<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>- |& O/ L/ p7 _3 C5 o* C
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>1 B( @+ d1 I# d5 @, ~
4 Q* p/ n, H7 Z  m3 @: R4 b/ l
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-4 10:16 , Processed in 0.068775 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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