飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

7957

主题

8045

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

) b& `& B  D3 m  Y2 ]+ ?7 R2 C<h3 id="一序言">一、序言</h3>- C( P( A. M7 x
<h4 id="一背景内容">(一)背景内容</h4>
$ w) G# P& F0 {: O; r<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>' ?9 [* K3 \3 E; C- ]; ^, t
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
  h7 e  s3 k4 }* E% S<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>' K: [$ L8 |0 {* F" v! Y( M! _5 h
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
& j5 Q# G; l$ B" V1 V& _- I! c/ t<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >9 e1 w& _! B& a& O+ B; q
<h4 id="二场景说明">(二)场景说明</h4>
7 {3 V8 K# h" m/ k<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
; W" f9 n4 X4 R<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
1 E3 s* }, b) e<h4 id="三前期准备">(三)前期准备</h4>! g( ]0 \' v/ K, u
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>6 y$ X& h" y$ F: }; K8 q0 U# c
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
% b$ O! ^6 ]* U3 k# `<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
% u* }$ O3 i" j3 f2 a0 h+ R" {<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>3 J6 @# R# R. T+ E- i7 U6 j% _
<h3 id="二一对一查询">二、一对一查询</h3>
3 t" [6 r! A: G( ?) Q<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>$ C6 n/ M, H& }8 @- ~3 y7 f
<h4 id="一查询单条记录">(一)查询单条记录</h4>
( _* L) z& a7 X2 G0 L<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
4 e1 ?/ s, P9 J; c% S9 i5 d' p6 y<h5 id="1示例代码">1、示例代码</h5>
3 Q( W: w# S  P<pre><code class="language-java">/**& m, v, b/ D1 }" E, {
* 查询单个学生信息(一个学生对应一个部门)
& m+ x' j9 V, k* x( z' [ */
! c! }, C7 e9 Qpublic UserVo getOneUser(Integer userId) {/ l9 B1 ?; d7 G+ d% H5 Q  n
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
  e1 c% @$ y+ f$ R        .eq(User::getUserId, userId);
3 L8 X  ^2 R! K, M    // 先查询用户信息
. V7 p! A6 v: D3 }* u    User user = userMapper.selectOne(wrapper);9 m! \$ R# |  K0 ?- h( N- M& ~: T& h
    // 转化为Vo$ [% Y: \8 m$ `, h8 ^( D8 a
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
+ n: `# t% n/ _    // 从其它表查询信息再封装到Vo( D; C- o; K3 ]9 Y  t. ?! `) E
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);& M: ~2 k( N1 b) O, L
    return userVo;1 U1 }  d$ Z2 \1 A5 P6 @: @
}
" Q4 g5 C. O+ D6 G& |& _8 s4 a</code></pre>
' V! Z% `6 D0 Y5 U' L( i# p# ?4 [<p>附属表信息补充</p>
) b9 Q0 \: c8 o+ {<pre><code class="language-java">/**
" p- ^- c. q5 Z% n2 F) b% [ * 补充部门名称信息2 Y4 N4 u4 S0 Q6 Y2 U* i
*/
, B1 P) c2 N+ i, R7 A! ?, _private void addDetpNameInfo(UserVo userVo) {' p3 l# V8 M3 l5 m+ j. H2 g
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
, I, \6 `  B! k( w        .eq(Dept::getDeptId, userVo.getDeptId());8 P! A8 C4 K4 L. U
    Dept dept = deptMapper.selectOne(wrapper);* P$ r' r( Y" G9 y: T, [% [4 G
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
% [* W0 T7 s' R; H}
  s3 l7 [6 \6 s( \+ j  g</code></pre>. b; M2 I% p& a7 i7 S8 l9 B( X
<h5 id="2理论分析">2、理论分析</h5>7 K2 D, w, W& o
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>  ~! d+ c( o& V% t8 }% q
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
% _% o6 Z* h) g<h4 id="二查询多条记录">(二)查询多条记录</h4>
/ q5 \. m) a: T$ k<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>  Q7 J2 X1 w; G7 S: U% H# u
<h5 id="1示例代码-1">1、示例代码</h5>3 {! H, m: t' S
<pre><code class="language-java">/**
  p, F- L5 O3 e% m, ` * 批量查询学生信息(一个学生对应一个部门)
6 w+ u) l* G, Z */* a" }# W' A: t% V- }
public List&lt;UserVo&gt; getUserByList() {
/ y4 v$ }. u7 j0 R7 I$ I8 n    // 先查询用户信息(表现形式为列表)
) H- l+ |, N8 z% U8 m7 g1 O9 J    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
+ Y+ z" L8 F" `8 z* R. P    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());/ j% C2 }5 N  c7 Z; H
    // 此步骤可以有多个! h. {$ p- L5 O$ k: W! r) ~) j( L* u
    addDeptNameInfo(userVos);
: R! g. b2 b8 C6 U. Y7 }    return userVos;, D5 |  h8 O1 C$ C9 J" {
}
2 W4 v* Q1 e9 a! c</code></pre>1 }( I. m; t+ _- n% h4 ?
<p>附属信息补充</p>0 n- R$ `, \# n0 w6 b* g# V
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {  B  B, ]) b( y% g& w+ d  Y1 M* x
    // 提取用户userId,方便批量查询
6 i. A5 r2 m8 `* x    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());. v3 i1 d% J2 |4 L9 l
    // 根据deptId查询deptName(查询前,先做非空判断). d" b6 ]/ O* r) w3 E
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
) X# b, \3 q- Y    // 构造映射关系,方便匹配deptId与deptName
  s( c0 T; z- V% \# _% N7 ]    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));% B5 t2 \* y+ F- ]: h
    // 封装Vo,并添加到集合中(关键内容)
: }' R0 k7 }. w. O$ n& y! O    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));9 g! J& t/ w8 V8 J2 g2 M
}
) M$ G& ]" b8 A* L% }, X$ |% [: \</code></pre>: s: A) a4 i0 z
<h5 id="2理论分析-1">2、理论分析</h5>. i+ X4 t* y2 S+ W8 d; _* p/ ]5 Q9 T# C
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
! W( t% S" [' T$ o# S1 Z<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
7 i7 _. f0 e; q! r% j<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
0 y9 j8 P' p; g$ S<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
6 S5 Z: {; |* P7 B  I<h5 id="1示例代码-2">1、示例代码</h5>
' ]0 d8 q. q8 ~% U<pre><code class="language-java">/**
- i* q3 D5 O2 H* _* p8 J+ b * 分页查询学生信息(一个学生对应一个部门)- w7 j, L% f2 m  K- x
*/
( L- H0 |9 r5 c8 z7 C5 o3 Cpublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
. H% D8 i6 K$ c8 I1 Y$ X    // 先查询用户信息# c0 |5 S/ A+ j2 |, Q" U" B+ M! o# `
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
& d. l  B0 i' ?6 P: j    // 初始化Vo' E% j7 s6 Y2 e5 X" f
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
& x( G( s' {' |& _    if (userVoPage.getRecords().size() &gt; 0) {
$ f+ y+ B$ Q7 G! B9 e5 S        addDeptNameInfo(userVoPage);
7 o& j; S+ \) \1 D- O, u    }! k5 g. e5 Y/ ^6 R. V; i6 d& p
    return userVoPage;
, _1 e$ a# v3 ^- J- v}! A& o2 x1 j) x2 m5 x
</code></pre>
& p2 K, H/ J" }: R<p>查询补充信息</p>
, \3 Z- x3 z6 U9 m: Z<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {, N/ K! |% K4 o+ K$ q( O
    // 提取用户userId,方便批量查询) q! N0 W: Q; W' }0 e
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
7 ~3 Z6 O  b" q5 Q    // 根据deptId查询deptName
+ c, F; F2 S/ u* z1 P3 W    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
2 z, X! W: n: z* _    // 构造映射关系,方便匹配deptId与deptName' Q0 t  T3 H6 W4 H; m3 ]% T3 U
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));4 j6 O! E4 D' V/ j4 e
    // 将查询补充的信息添加到Vo中
0 S1 p! o7 p0 k$ T    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
( u+ X' e0 g; Q" o1 v}
" l) A( l* ]( E2 i</code></pre>
; z  G8 x% v1 h/ P) C<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
+ M3 c; ^' N% k$ [' z. d<h5 id="2理论分析-2">2、理论分析</h5>
2 q( T1 }: u: v: a<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>! I/ U8 ^, \' x
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>4 t. D2 g6 z6 `  f% k- {: R2 F
<h3 id="三一对多查询">三、一对多查询</h3>6 @/ N& \; W: Y0 Y: l. y
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>; x2 K: k) p$ N* @. B
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>( m$ G9 T& f& H) y0 R, l$ b  _( C
<h5 id="1示例代码-3">1、示例代码</h5>
: m0 w! z! r1 c<pre><code class="language-java">/**
8 b$ X5 I0 {" p7 B * 查询单个部门(其中一个部门有多个用户)
; B0 p; z3 s6 L9 D$ R) ]! d */
0 ~% L) X. [- q6 S0 Npublic DeptVo getOneDept(Integer deptId) {5 y9 R* t1 K3 Q  a+ w" x! D
    // 查询部门基础信息5 L" }  g7 ~% _! O
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);. k, H5 s4 D7 ]2 G+ N9 l
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
/ d% U  B3 n3 m    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
; y6 J& k( Z8 w3 V9 C    return deptVo;( M- P' `% J6 L) q
}
' A' R% U% q# A+ ?: P. Q; h</code></pre>
, w$ m; f/ g+ B0 O1 h9 W+ v<p>补充附加信息</p>
& U5 \: s( h, l2 l2 h5 p2 t9 V<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
1 `0 g; e- b, Q2 B% f7 j    // 根据部门deptId查询学生列表8 `/ Y4 Z3 Q8 ^; s3 f& s' e* b
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
" G! Z, K/ g9 X" h+ h5 o' z    List&lt;User&gt; users = userMapper.selectList(wrapper);
% h5 [/ ^7 O! q! P) T    deptVo.setUsers(users);
4 ?8 t% L. `% n3 A- z}
  S/ ?$ b: C6 d& T) r</code></pre>7 P9 A$ k# Z. h1 o
<h5 id="2理论分析-3">2、理论分析</h5>
0 \5 j  v, @1 D<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>$ r2 Y6 V1 N2 d$ P8 v
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>6 [$ d7 B: l! T" x4 s
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
' i8 T, a: I" m: |/ [6 h<h5 id="1示例代码-4">1、示例代码</h5>
0 O4 h5 \+ A% i/ v1 r4 N& k/ s" o+ L7 S<pre><code class="language-java">/**
2 w3 y: ]9 l9 p) W) v# s, f * 查询多个部门(其中一个部门有多个用户). K; q2 D- A+ B0 s
*/3 j9 J6 W5 C8 q: A/ ^. r
public List&lt;DeptVo&gt; getDeptByList() {
: s- Z0 r" ~  R    // 按条件查询部门信息4 r  T' X( T6 K2 E& ^+ A
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
- A# v2 s; @/ x1 W3 \    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
/ `5 C! S( R4 ?. p    if (deptVos.size() &gt; 0) {
, Q( X; ^& E) Q7 E! W: |+ L        addUserInfo(deptVos);
6 K1 F1 l# U/ L. C$ _0 s5 P    }
2 P* T$ O: Q+ ]7 Y- h1 p. k    return deptVos;
. ]5 a: J4 Y0 g4 b$ p8 v5 `, l+ H}6 d+ v2 G2 B7 u6 N
</code></pre>
1 P* c- b1 e* ^9 }9 }" o' c<p>补充附加信息</p>
( @( t, [8 R7 ?/ D; T- q! l" |<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
5 O/ z4 s2 R4 U6 P6 I    // 准备deptId方便批量查询用户信息/ x  S1 _" c& G3 C9 j4 y7 c
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
: r# k" S% r* I$ S2 D$ ^0 L    // 用批量deptId查询用户信息# L1 T7 s4 `9 O4 s, {
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));* l; x% h6 l2 K. D8 }! L; ?( Z- J$ l
    // 重点:将用户按照deptId分组. @( E+ F# a5 n9 J, z, `
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));, @  I* Z" F6 O/ h# b  c
    // 合并结果,构造Vo,添加集合列表
5 f* K. E6 e3 _/ e    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
* F3 O7 @6 f8 t8 k3 I+ B) v# L+ m}! m' l  H2 v2 ]8 B8 u
</code></pre>: U( m/ x5 K% X3 X  ]/ ?* _! W
<h5 id="2理论分析-4">2、理论分析</h5>
0 M( F' j; E* |& C! w7 l<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
% S4 E6 C/ l+ A) H3 W9 X" C6 ~<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
- t& j3 V- _& i; l7 `<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
% f; G7 v* h4 j, @# t<h5 id="1示例代码-5">1、示例代码</h5>5 B, v2 Z  v+ Q5 d6 J( r
<pre><code class="language-java">/**
9 t1 D8 v6 F0 \* f * 分页查询部门信息(其中一个部门有多个用户)
3 f8 ~" q' |2 Q% |  d9 D */: S1 \8 K. t6 \5 [1 f
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {, X$ o- ]0 g0 B
    // 按条件查询部门信息5 w. z; |; |7 _  B: t$ x, [
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());6 j" ?' e5 a: l9 w5 `
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);9 Q& ^" K& D5 g
    if (deptVoPage.getRecords().size() &gt; 0) {& p5 p: e& M6 u5 h
        addUserInfo(deptVoPage);3 \5 n$ B& D2 _& E0 E2 l) v
    }/ M+ ?$ r" o0 a1 {
    return deptVoPage;7 J0 s. i6 T% [9 q1 i2 a
}
( C/ r0 ^! @: s3 Z3 I</code></pre>9 _0 g$ Q2 w6 E% @
<p>查询补充信息</p>
9 H9 {% u* k0 i; n! W* y" i<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {- ~$ B* ]! s1 s! K8 n) |8 |
    // 准备deptId方便批量查询用户信息
# A* [3 j! O  w: R    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
( M6 U3 c1 ?9 n/ T$ [    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);2 J6 {. y( o9 G% T6 m
    // 用批量deptId查询用户信息
5 N3 A2 S) q6 n. j, |* w    List&lt;User&gt; users = userMapper.selectList(wrapper);
7 A  S; }$ H: I: P    // 重点:将用户按照deptId分组
( Y: {1 e5 D; ~6 J    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
: h! u1 g# a. t, K7 G- {6 R) p    // 合并结果,构造Vo,添加集合列表
* E% G& U/ g3 d7 Y1 G( D$ j    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
* t  i6 e- d% `1 s" [' }* L& E6 X}1 @5 x5 g$ S' X, r' k
</code></pre>
) A& y/ K! j$ _! F  F<h5 id="2理论分析-5">2、理论分析</h5>
* _- t0 C; B& q/ Q& n: I# B2 Z. U<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>  |: e+ y1 M/ O& m" B
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>/ C: P: n: d2 |* r) _3 M" r
<h3 id="四多对多查询">四、多对多查询</h3>
6 C  y4 X8 I8 x  }<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
; g9 A2 L& q- J5 A<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
0 d' w! Z  ^' z( o1 v<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
9 k% f1 V) k5 i. D4 F8 n<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
( A/ I9 v0 a, ^: L5 ?<h4 id="一查询单条记录-2">(一)查询单条记录</h4>, D) H5 g) K  n. P
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>- L) L' {6 ~% |. x4 L& g8 Q  w
<h5 id="1示例代码-6">1、示例代码</h5>
, Q+ j, D. Q/ O: ]' i  R9 t7 z: r<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {# K/ A# L6 w& ~! Z) g8 {- Q3 F
    // 通过主键查询学生信息7 I$ G% N. F3 u7 F; c7 W
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
/ S/ [& b  R& d* E0 z9 D! o    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);! p) l! v6 g' O
    // 查询匹配关系3 `2 e; h4 ]! R  y
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);* h& Y( O8 G0 t  v
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
6 T$ ~6 O4 ~/ y" F3 v8 D    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
4 r( i% w2 e$ _8 L$ e2 r" b        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));! }) N7 h9 w* J/ Q0 L, i
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);0 d/ ?/ G7 r& g, X; s) L+ E
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
% }. i+ }- ~* S: ?5 n- I        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));0 F$ o5 E+ ~1 o2 }( C4 l  n( H% m
        studentVo.setSubList(subBoList);- }- V3 J& C& D' m
    }
3 M: O  q: D* I7 I% M# k$ k( X; y    return studentVo;* X: w6 w2 e3 t' l: O9 u% D  K
}  |( l/ |+ I. |
</code></pre>
5 ?3 k9 s4 {; N+ R# D& F7 U<h5 id="2理论分析-6">2、理论分析</h5>) i* g* m$ V+ B5 N: T
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
: M* s! O/ ]1 m3 J0 N/ u& v9 H# A<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
( g" a, e) s4 A; w5 s<h5 id="1示例代码-7">1、示例代码</h5>
' s4 Y) p5 o; q7 y8 ~8 M/ p<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {8 L- W) m( A# X/ S) ^
    // 通过主键查询学生信息
) x5 n+ y. [) G    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
+ I$ p$ ~9 }$ J( S5 g& U  U% e    // 批量查询学生ID
6 s$ X8 G4 }0 ?  K    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());; P* B0 G1 a1 z; l3 z0 y+ u
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
  u' W& t1 x' h  }+ ]# u    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
; o( @* S9 F/ A; i* b/ i" ~! B3 D    // 批量查询课程ID
/ w1 t3 ~' E9 H) r$ `+ r( l' ~    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
: `8 m7 S" [# _9 w    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
7 ?- D1 }1 ^; i        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
9 O& f. y$ t( F2 F( d) \, i  o        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));  M; M0 n: l9 c0 @* v  X6 _; b0 o
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);. D/ s- O1 V( e+ |
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
2 q8 K; s# m4 I/ t2 P: V        for (StudentVo studentVo : studentVoList) {
0 n; g- Q! u% j% G  D5 O! B            // 获取课程列表
3 Z* h  J5 q# |            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
) @3 C" V# V0 @% N6 B            // 填充分数. }# d4 t- f! i- K* D
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
/ B; T/ ^! j1 n$ Y            studentVo.setSubList(list);5 `" w  U/ q' I2 I# I
        }
! H0 _1 d% Y( b* t    }0 L( B& f) H4 \9 \
    return studentVoList;0 ?: S  `/ B/ d, q/ |0 l! h0 x. X
}
0 e8 ^+ k( Q% A9 O6 N! V</code></pre>
0 t4 ?9 t: h% s8 x1 q3 p<h5 id="2理论分析-7">2、理论分析</h5>5 q% w/ z$ ?3 u# P5 Z4 g
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>; q* X: P" S# f
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
: h/ m! A; u; Z: L% V: @<h5 id="1示例代码-8">1、示例代码</h5>! x2 G" D: o0 [2 g: }8 M  U4 L
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
* y# r- K' h' t+ B0 I    // 通过主键查询学生信息
: v. Q! _: }2 K6 k) c5 |    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);. i8 U1 K6 |+ g( r0 w: s
    // 批量查询学生ID: l$ m3 x% ~5 A& Z
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());+ I# s; [1 c. T* |. p
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);# m5 f2 [' k) J# C; |. T
    // 通过学生ID查询课程分数" D! s; I' }" z0 E$ n' V" c
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
: }5 C; U" L) L0 ?3 w2 [( t$ s    // 批量查询课程ID* s* A+ }& X/ R# Z9 [3 L# l; @
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
, H: r- Y8 y/ m) e+ k4 Y! b    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
( l! G( X0 k. @        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);- ~# s" n" s4 L! u
        // 学生ID查询课程ID组
  _& j) X0 I0 @+ \; G8 X        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));0 s" I* D$ L, a) v5 x

( B% e! s! i2 t- z* N/ X" {& [  y        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));- j: _# [( P( G. t
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);% o5 T& {: b: \" i* J. a
        for (StudentVo studentVo : studentVoPage.getRecords()) {
$ V7 f3 |3 Q" j0 s( |% w            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));* U8 ~1 Q9 y+ E) Z
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
( j, S7 M3 S; }8 \: e( p" |            studentVo.setSubList(list);
- w9 C  Q; B7 w8 g) l* f        }
! ?) ~, w3 n/ {" n    }
& o. j6 B: {; ?4 \6 L4 ^' u4 g    return studentVoPage;+ a( s+ x" e. i+ w
}
& [; a2 U8 d# a</code></pre>
0 R# z5 K5 l  _6 |  M<h5 id="2理论分析-8">2、理论分析</h5>
3 j' R% _) F4 U* C; D1 N' y<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
6 @. f+ d+ X& |; O<h3 id="五总结与拓展">五、总结与拓展</h3>
' b* o) I# u* A; w# h7 ~+ X5 ?<h4 id="一总结">(一)总结</h4>
7 y% v8 v: L1 ^: N. V<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
4 {$ k% ^: m4 X<ul>
) q: t" e! G2 ^, J" A3 x+ d: M" A<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>( Y# l5 w) [3 ~9 @4 \
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>8 S) ?2 W/ g( q) h* m2 ~  e% W
<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
) m$ v4 A: e3 f  Z</ul>! N# b- L0 `* ]: d, c
<h4 id="二拓展">(二)拓展</h4>
; b/ I8 j2 w8 `# Y<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>9 E+ ~; c( u4 M. W( S
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
+ \, W$ X& ?" x7 {7 z<ul>
/ _/ P6 O4 n* I2 v- t<li>当数据量较大时,仍然具有稳定的查询效率</li>
" Q2 a' f) x3 s  U) k/ B</ul>
: z) [5 {8 a$ ^6 Z<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>  M& k' }" f, @5 [2 D
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>3 r. q$ t# D/ C$ T2 s2 q
<ul>
# \7 _3 n8 ^. h. D<li>与二级缓存配合使用进一步提高查询效率</li>
8 l8 Z# W+ }" P/ R' g" R3 Q) O# x</ul>0 u9 t: A  q7 B
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
* k) |9 e: C- ]$ t3 G- h<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
; ^' S" j+ }9 o7 o
$ I) o8 g1 A% i. e0 J  L1 {. _
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-11-26 02:21 , Processed in 0.075064 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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