飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8242

主题

8330

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

# ~- h9 Y4 U, E0 Z<h3 id="一序言">一、序言</h3>
9 w9 P; h4 o1 I4 a) O8 ]! |, B<h4 id="一背景内容">(一)背景内容</h4>7 o) Z! A& q4 f  |9 w* d( \8 ]+ [; Q8 q
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
4 `' v4 d) u& V3 n! V6 B  Z<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>, s! O$ C* i1 H) t: |7 |! ~
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p># i% {3 Q: n* O$ A! A
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>( J- r6 w) d; l9 Z1 m. G1 `
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >2 w+ _$ Y6 `1 R7 G0 A9 e9 F
<h4 id="二场景说明">(二)场景说明</h4>
& k' G+ L% A! h/ W6 v<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>" Q7 q3 E" _$ R& ~7 }0 E, {" |
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
" K  ]  z) y5 W" ?8 n<h4 id="三前期准备">(三)前期准备</h4>4 {" Z, D" g' x1 k5 `1 o
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
6 m; C8 f4 w9 [" F- O<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
6 W2 Q6 q$ w; X$ D. h<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
$ t& w# d6 u( s: b  Q$ W+ I( B<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>- I& e2 q6 J5 E( ?# L! y  `
<h3 id="二一对一查询">二、一对一查询</h3>! m6 `; E# \3 a: `, [
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>5 ^* x7 s( T" L/ [( a* y
<h4 id="一查询单条记录">(一)查询单条记录</h4># C* U1 c! \0 O8 r4 }
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>- @6 S$ I3 g( c1 C0 E; v
<h5 id="1示例代码">1、示例代码</h5>
! W* c4 b2 L8 e4 f9 W! l8 S<pre><code class="language-java">/**! Z# y5 S% m6 D) a7 W, g
* 查询单个学生信息(一个学生对应一个部门)3 c& T- u4 N- x7 A! _
*/' l) `0 P' f9 U
public UserVo getOneUser(Integer userId) {9 c" e2 W; r5 d, {; U
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
3 O% T" z& }$ X  }. ^* ~. G        .eq(User::getUserId, userId);) @5 F: p* Q' e0 B# D* N2 h
    // 先查询用户信息
" l6 @8 z. m1 Y0 ?6 @    User user = userMapper.selectOne(wrapper);
5 z7 b2 w+ x0 F# p; W5 X    // 转化为Vo$ i  M3 ?5 [; [$ `" e" l* u/ x
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);/ w( s" B, W" ~4 I2 B8 x* |( f
    // 从其它表查询信息再封装到Vo
: S* P0 P5 m$ K1 m5 r    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);! l# H5 P4 a4 l
    return userVo;( b9 z/ I. ~. w" I" J- J
}
9 J' ], A  ^# k. T( l2 r. @</code></pre>0 W" _1 }/ _4 i- N9 _
<p>附属表信息补充</p>  G1 P" K! a1 U9 \8 f4 C) Q
<pre><code class="language-java">/**
* b5 z2 {/ r% t8 p * 补充部门名称信息
" h" f1 N. q1 ]3 k  A# F */
  ]# Y: I3 ^! r( Fprivate void addDetpNameInfo(UserVo userVo) {) u; e: h7 q& v- O/ C
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
% ]$ ]) |7 R2 A8 P3 ?2 M' p6 ?* W# b        .eq(Dept::getDeptId, userVo.getDeptId());# S5 y% K# U& q& c( `7 ]& q* s
    Dept dept = deptMapper.selectOne(wrapper);" _8 e2 H; \/ P  T) M
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));5 R7 l( E; ?/ \- O
}
. w$ O% W' R" f) U0 ]$ X</code></pre>6 {5 w% B5 V% k+ @4 f: O0 C, A
<h5 id="2理论分析">2、理论分析</h5>! L  I8 e* n$ R9 g
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
" ^! t+ h: G( ~& a+ o& d<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
$ y& `3 Q7 B5 S# E( T8 n# C<h4 id="二查询多条记录">(二)查询多条记录</h4>2 W4 f/ \  P8 F
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>4 c# ?. a* n3 N9 J
<h5 id="1示例代码-1">1、示例代码</h5>
& A/ B$ h) ^: l! @8 V! V2 D  s* W" M<pre><code class="language-java">/**
& N8 \: w+ K, o8 l- v * 批量查询学生信息(一个学生对应一个部门)
! L; F* k+ ^4 Q- x8 ?  {3 G */& S1 m, G5 e  {; a; N% Z
public List&lt;UserVo&gt; getUserByList() {
5 p! B3 \2 \9 F0 c! C( S    // 先查询用户信息(表现形式为列表)
1 O. ~( d# V9 Q    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
) G7 m0 B2 Y% t3 U) Q    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());& m4 j% h6 K  H% W0 t% T) `7 p
    // 此步骤可以有多个
% i3 _/ z/ |! i0 a6 L: U3 k1 t5 R    addDeptNameInfo(userVos);" S& W. H( V  k" ?7 H2 p  l
    return userVos;
% |! Q# n8 ~! p, i" S}1 U5 T  w) {( s5 G. p
</code></pre>
2 A& J/ x4 h7 f' n8 j& v<p>附属信息补充</p>; E4 D3 b$ l6 B2 w( l1 u& [3 C
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {. F) N% S! f& s4 x( ]1 b
    // 提取用户userId,方便批量查询
, W2 E1 W- d* i: Z) H2 \3 E9 ]    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
( |0 Y- u' }! r. Y- V! x  q    // 根据deptId查询deptName(查询前,先做非空判断)
" r( R9 P# P+ G5 h) Q) g3 M    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
* A: _: N2 x4 I) v    // 构造映射关系,方便匹配deptId与deptName
, x: f; c0 g. I* j    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));: j( t( L; e' ~0 R
    // 封装Vo,并添加到集合中(关键内容)
' U4 m5 S$ S. O! ]. \    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));  N9 t9 J0 i& H! V
}0 Y9 y2 f  B) R0 |
</code></pre>9 A5 F) h" N! S  A$ b
<h5 id="2理论分析-1">2、理论分析</h5>
4 P& Q3 }$ E) K6 K& U, r<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>8 m) l" K- y# t# @
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
2 b% ~; O' f. h4 e8 `) ]<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
; \- q4 T; o; h<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>/ y! _: v1 b, ?; n
<h5 id="1示例代码-2">1、示例代码</h5>
3 l4 r, u% P% w1 S4 ^# {<pre><code class="language-java">/**2 h0 r  }1 |/ o: n9 _' \7 O5 L* t; v
* 分页查询学生信息(一个学生对应一个部门)
1 K' U; D- d) i; U* @/ ?% W */
! U3 U3 G$ P. n0 f! vpublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
  i+ l9 j4 n$ S% D    // 先查询用户信息* Y$ |7 Y" K, g) D2 J
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());0 S) ]2 w- U" J  R0 U
    // 初始化Vo8 ~. V6 A+ w8 W; w2 d  y
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
- g) ~( X0 t- s+ s, Z) K    if (userVoPage.getRecords().size() &gt; 0) {
8 p, Z9 |0 n$ M: `6 d# z+ S2 T        addDeptNameInfo(userVoPage);
3 h8 N9 D1 p( Y% d  a    }
) A4 X/ |' ~1 e( v- ?2 A    return userVoPage;' p- x* |" P! u& Z' Y9 O
}
7 H* N8 r7 i* F/ D& j2 {$ L</code></pre>
4 B" l* J* P) O( _$ y5 n9 {( J; @<p>查询补充信息</p>
% O$ C" a% R: C9 P" a' H<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {6 ^7 }# K/ r- `5 j3 A6 x
    // 提取用户userId,方便批量查询
2 z* w, O5 ?; v8 Y' t    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
8 l8 Y$ R. X$ ^/ Q* R/ e- u* d    // 根据deptId查询deptName
3 P0 T% c$ d2 J3 Q    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));" w/ J. ^. A( P# E
    // 构造映射关系,方便匹配deptId与deptName8 v8 N4 @8 `( I- L; s
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
& F/ T" n6 c$ m0 `    // 将查询补充的信息添加到Vo中
* D5 f6 K$ n2 U' M; u0 m    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
( a5 y# p" r2 F9 l: q}
. q, v5 Y. X- a7 N5 l& _9 x7 L3 a</code></pre>9 U$ o; p9 L% s
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
. Y% N1 m9 v9 d% _& ~" {: M4 b  ~% f<h5 id="2理论分析-2">2、理论分析</h5>
+ L6 \. F4 }) K* V' s5 ^8 x  t<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
, E; g" m) H' A4 m; V9 W- g<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>  P6 n, @; K# K( i: e3 u
<h3 id="三一对多查询">三、一对多查询</h3>
$ Z+ b; ~$ ^- a/ g1 e7 L<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
! P7 R$ H! h" m<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
! w! I$ C( e2 Z<h5 id="1示例代码-3">1、示例代码</h5>/ D/ G: U. c: Q- l+ ?, Z
<pre><code class="language-java">/**
- D, }) O$ w7 n$ \" ? * 查询单个部门(其中一个部门有多个用户)
1 [0 ]1 A0 ^  t+ S8 H. v* [& H */
9 Q: ]. N. F( p: N  r" d9 x  Bpublic DeptVo getOneDept(Integer deptId) {
7 i$ V. \6 j- n8 G7 q  `9 C/ F, A    // 查询部门基础信息& e; b* V4 Z/ d* T. y
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
# `' W) I6 R; {+ n. b    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
) \# p+ L4 F! Z/ {    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);0 [- o" y1 x( [. M5 x& v9 i
    return deptVo;* P  F4 |+ A2 N2 E
}
+ |, `1 A% p9 g. D) Q</code></pre>' e( O, ]  O8 F8 I7 v/ I  m
<p>补充附加信息</p>7 V" a8 e; F8 U' ]
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {4 d' t  g3 A; d3 h: o) [+ \4 u& [
    // 根据部门deptId查询学生列表$ n0 A0 ^  A" p0 K
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());- i: x; D, P- t
    List&lt;User&gt; users = userMapper.selectList(wrapper);+ t: G4 |2 S3 t3 Q
    deptVo.setUsers(users);4 q! p9 k2 _/ T$ D) h3 f
}- E2 c0 r9 ]  R' ~+ l0 ?
</code></pre>
$ |* T0 S1 {2 W4 w! ^( G4 |# U<h5 id="2理论分析-3">2、理论分析</h5>
) r8 b* ]. J7 n2 P/ Z" k8 W3 g) i6 c<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
, n$ Y* Z9 |' m! H+ q1 o<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>2 Y! `# w+ [7 o; s. [
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>8 o/ g- A* j6 L2 |0 |
<h5 id="1示例代码-4">1、示例代码</h5>
( ~, X/ N' W- E<pre><code class="language-java">/**
" z% S. L2 ^0 l; A! W- ^! _$ o! e * 查询多个部门(其中一个部门有多个用户)- M* \9 n; R# g0 b7 K
*/
9 L7 u+ L3 z1 N7 Epublic List&lt;DeptVo&gt; getDeptByList() {
7 _! D- }) h: P! ~" j, g    // 按条件查询部门信息( ?1 i' D% x! d7 v2 g- y
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
$ T. G6 r, k- \2 a$ E* z' J+ L    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());. m+ ?) f9 P( |+ }
    if (deptVos.size() &gt; 0) {
0 l) g# p5 m3 H! M6 N2 [        addUserInfo(deptVos);( C  \3 f! e- x; `
    }
+ J+ R( x3 v$ |& J3 z; h. P/ |    return deptVos;
1 ]" q2 b; w: e  W8 @}
3 f+ ~- w' r, g% h7 M& \% V' `5 o</code></pre>% E0 |5 q3 u9 i/ v; ~  ?
<p>补充附加信息</p>8 R" n9 m7 T+ P  K, I9 |
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
: f7 b1 Y  B, {' f! h    // 准备deptId方便批量查询用户信息
$ o6 b2 x5 j, O. A6 ]+ P9 t6 v    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
7 [# S; @$ F* S3 L, S    // 用批量deptId查询用户信息
" D* c7 T4 T% H9 Y8 t    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
% i) j* X+ t8 ]' Y% g3 m    // 重点:将用户按照deptId分组, ]% k3 f' t  {6 f/ X* ?
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
9 W: U5 p/ L. ?3 K, N    // 合并结果,构造Vo,添加集合列表
0 D& h- i2 \9 ]; ^% V    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
/ g9 [) \7 r. c/ p# b. S9 \7 z}
, u( g( Z4 n' ?. l( B4 I</code></pre>4 i! D  F& e: s) {
<h5 id="2理论分析-4">2、理论分析</h5>2 O1 I% k. z3 X
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>" o- Q6 ?2 K6 m' |3 E
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
9 J$ ^& a3 g+ c2 R. [2 X<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>7 c7 p% y/ S% M3 A: X' K) k; C
<h5 id="1示例代码-5">1、示例代码</h5>
; {- ~3 z# x; a: M! b<pre><code class="language-java">/**# O0 P' ?$ F) f
* 分页查询部门信息(其中一个部门有多个用户), S1 O4 v1 K. Y, P% {' _
*/: h5 t, Z7 b% p" ]" ^2 i' k* s9 m
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {; D& D$ Z7 n5 _' {
    // 按条件查询部门信息
8 S/ V9 H3 @" w3 ~2 A0 ]    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());0 J+ m! E+ W" W" l# g( @3 P+ _& B
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
. G2 }3 i' k; o    if (deptVoPage.getRecords().size() &gt; 0) {
. Q  p- k8 G. O- S4 P. q  [        addUserInfo(deptVoPage);
6 w2 k7 i" Y1 Z7 Q/ b0 s    }7 w0 j+ j" t5 `4 z% s
    return deptVoPage;
( g; q5 G* V, m8 N' t) T3 d) D4 w- {}  `: R+ [. y1 m( K( \$ t
</code></pre>4 ]. a* Z# }6 O- Q& J, l
<p>查询补充信息</p>
) A! z9 J( V# s* B4 c% m/ }; D. L<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
% c$ Q6 C/ m+ i' z! S) y    // 准备deptId方便批量查询用户信息
# _# d; j4 s5 H5 \  l5 A    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());" O* j. f) b6 P1 ^% S# q4 x
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);+ z8 H( B* l1 d. J4 n" Z* \! L( v; ]
    // 用批量deptId查询用户信息, z  d) ^3 r$ r
    List&lt;User&gt; users = userMapper.selectList(wrapper);* M% p& `& O/ ?4 L8 c; P  J. [
    // 重点:将用户按照deptId分组* s! F& e. J  L/ f) |& ]! p1 n6 f. o
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
) F- h) A# `6 L! q1 m3 X+ x    // 合并结果,构造Vo,添加集合列表/ E1 E( `: I9 T1 y& E" v7 O9 @
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
2 d5 I6 r* I3 x( Z8 S6 X/ i- Y}
, F; G4 z; [+ j& c6 Z6 P9 u1 {0 d</code></pre>" m( d  V# k) p3 m3 `) \
<h5 id="2理论分析-5">2、理论分析</h5>
+ x2 G6 @; g3 d  _2 {4 C<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
  K! h* o8 ?9 B1 @+ V' J$ G& h<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
! I* ~, A6 L( @% a. [<h3 id="四多对多查询">四、多对多查询</h3>; [2 d8 G/ \7 @& x  R; q6 W3 c$ u
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
" b# u+ H& U1 U<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
" C/ d- }0 Z" u, X, W! B4 }<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>; S: k" i+ @! b* H; t, k
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
6 N' K2 I. R# i% s<h4 id="一查询单条记录-2">(一)查询单条记录</h4>5 ~6 n- @- _3 ]8 ]5 L$ d* I
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>  M: V" X; H7 @8 |& {( j  H
<h5 id="1示例代码-6">1、示例代码</h5>
- X& J6 g5 t; L<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {. J# \9 u6 m3 a1 L) A% @  Z- S
    // 通过主键查询学生信息+ q: |+ d# S0 Q7 q  d4 B4 E3 g* K
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);9 S/ X- e+ o- }. n. `; g) b7 F" X8 R
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
, R- u0 o6 I/ N( Q# }5 w3 A0 k    // 查询匹配关系
2 \. T2 m8 U/ }    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
2 O3 y0 |6 v0 n& C. q6 K/ v    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
: p# w7 D9 |; w0 J+ f    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {0 J" o3 p* W$ o+ e9 ?
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
/ d3 u, @  _$ c7 Y        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
9 G  ?, i; |2 B! w        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
' v! c$ F# y% _0 C        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));# f& G6 i8 Y5 m
        studentVo.setSubList(subBoList);0 f3 n* R* k* @
    }
( K  g; N7 E% t7 Z+ R9 v  j  H% T    return studentVo;
* `( t" r4 m( D: Q# I}
% _; P) Z9 a7 t% x2 q</code></pre>3 j& _% T+ I6 ?- r
<h5 id="2理论分析-6">2、理论分析</h5>& w/ Q0 F( [  n, ?9 x
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
6 t4 S6 j9 M5 Y+ B, m1 J3 W5 \" n<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
4 E/ \! ^  s4 J/ ]<h5 id="1示例代码-7">1、示例代码</h5>$ e  P- E4 t+ m
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {( p( O# n" w/ ~8 a, T" |+ P- L
    // 通过主键查询学生信息
( b( e% Y9 u5 v# v4 F    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);! R* U& |" \3 j
    // 批量查询学生ID9 {3 _' j8 x+ ~/ l6 |
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());7 i$ y& S# n! R3 A
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);% _: M2 w6 B& l& Y
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);9 Q) ^- a& x$ b% ], p( G  V
    // 批量查询课程ID7 @7 Z1 \8 O; \/ }  h
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());. {; y) E$ d* E5 [+ M
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {! U5 s! l" q5 H$ u$ J) R: ^2 L6 _
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
+ l- g! j" p: N* r- I4 `        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));5 ?& N+ |7 Y* d! a" Z
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);  s) g5 S3 a4 s% [- |: N( e
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
# M1 l9 G# t5 {/ R6 x& H1 l        for (StudentVo studentVo : studentVoList) {% C) U: v3 w% [/ G- h
            // 获取课程列表
  C- ]7 |0 r: H            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));; S+ ^' G, ^6 V6 d
            // 填充分数) T7 u% {9 l& G# B* ?* c; I
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
3 p; ?$ x5 ~/ j' R2 K            studentVo.setSubList(list);# u$ c7 }4 o* ]6 Z" w, L9 ^
        }
9 V5 x- Z6 B- y2 ~2 T: I    }
( P7 @5 h1 E. G, @. W- _    return studentVoList;
! }- j2 g3 U) {3 }4 a* }' a2 O}& h$ N  Y6 ?7 X
</code></pre>: B& C/ I4 E: y0 {5 g
<h5 id="2理论分析-7">2、理论分析</h5>" R) X% Y" z1 C% L8 r
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>2 a$ F. ]% i+ j2 \
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>4 b# Y$ \5 X) S; t4 L* `5 N8 `
<h5 id="1示例代码-8">1、示例代码</h5>% Y$ u) H1 @! \) F/ ]( b
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {9 t: v! s- u/ H  Q+ |
    // 通过主键查询学生信息
' Z& g+ w5 a  x; f2 n    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
7 H+ Y9 ?4 W: g" Q    // 批量查询学生ID
& I2 X1 m5 U- p$ ^    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
' g" x8 _9 }+ J% a& H+ k/ W    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
1 V# E% L# t4 x# `2 a1 p    // 通过学生ID查询课程分数3 v( _$ @/ c7 `4 M% ?& E! y
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
4 u  M; @$ ]* w/ Z- q    // 批量查询课程ID) a$ \3 X. o$ x
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
# s% M: ]5 H! u1 j# X: P    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {0 s, E3 A/ Q' s- ^3 E
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
" Z: N+ ^, Y, H2 s* r; S        // 学生ID查询课程ID组! t# v$ v4 i) }9 e: @5 c8 {0 c: a
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
" J, v* e6 K8 c- J9 B  K+ u! U4 T5 F8 \, c- V
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));( _% B% I- b2 R3 t# `
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
& j$ w4 ~! {+ {+ b; S/ E) K6 V2 I        for (StudentVo studentVo : studentVoPage.getRecords()) {
8 O! X1 H- t& g            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));1 f; E6 T# q" S$ q) K$ ^2 r2 j
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
: L/ b0 j$ b2 W3 |# ]' Y* s1 a% ]            studentVo.setSubList(list);
  o- A% E8 m  s  ?! J9 }        }
0 t% {' M: j  }8 o* B/ ~    }
: \: o  E/ B) @" K    return studentVoPage;
5 N1 y# r# B; Z& B, S}
" [. E7 X- `0 z" I2 o! t</code></pre>
8 Q- Y4 `9 E: T3 k! M<h5 id="2理论分析-8">2、理论分析</h5>% j+ ]' r7 p! k& ^( y
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
5 x0 k! I+ a6 b  [0 N7 c7 j% }<h3 id="五总结与拓展">五、总结与拓展</h3>- i4 `" w. i) U9 Y+ s( N6 B
<h4 id="一总结">(一)总结</h4>
6 O0 u8 j  }; c* F: T<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>1 I4 k# a/ M; ~( M- V
<ul>
) Z6 T1 z: P; _3 @; v: q! R<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
- f+ w# [+ M9 M' s/ `  P<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
5 K" ~# b% f2 t, U7 t. u<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>8 t3 Z' V/ e9 M& {5 y6 ^
</ul>" y( M/ Y6 U3 o+ |; i& k
<h4 id="二拓展">(二)拓展</h4>
& \" W& T# `* E% y" p8 h& Z<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>( A/ Q( [# a8 D7 T: Y' ]
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>1 ?$ F7 V5 m4 l* |5 f; K. p
<ul>
$ r& a7 v0 M- h' o1 F; y& Z<li>当数据量较大时,仍然具有稳定的查询效率</li>& v# D: n3 C" L) ?6 A
</ul>; O4 P' u8 h  r1 X. s
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
. s! T0 |9 l* B, _$ R0 {<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
' T. m+ R$ |% ~; \: A, \6 A& J<ul>
: z: Z4 d! r5 p! E9 @2 I9 s<li>与二级缓存配合使用进一步提高查询效率</li>. ~9 B9 F6 z% Z( S
</ul>$ l/ X) {8 X3 C4 ?& a
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
1 V) `1 o1 g& v$ Q<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
9 [  X0 ^8 F5 Q! ~
1 @2 L8 @2 @# R+ K; R
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-1-14 03:42 , Processed in 0.066567 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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