飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7673

主题

7761

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

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

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-10-26 20:39 , Processed in 0.071518 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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