飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

6806

主题

6894

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

; p* p3 v6 o/ i! G4 S<h3 id="一序言">一、序言</h3>
" H- J) b  U) n! E<h4 id="一背景内容">(一)背景内容</h4>$ _" U9 n- B9 o" s' k( k' c
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>& V2 |* L) q* N  A" m
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>. }" P+ y) M+ q2 X5 d) ~
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
+ F+ y2 g' z1 w7 C+ ~<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p># N( k+ c+ ~7 N: M/ H7 S5 y
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >7 y8 O% k5 Q+ ?9 c
<h4 id="二场景说明">(二)场景说明</h4>5 j- ]8 F( }- y
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>! N, V7 z1 s8 q( j1 h; C8 w/ I
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >& a; N( t) r! e2 r" h; P# C; z
<h4 id="三前期准备">(三)前期准备</h4>
6 j4 s: I+ t: ]. A  q" d9 l<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
2 M  b( Z+ ~1 o  {<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >$ v4 ^9 x! B0 _; O; L
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
: }3 L+ W2 P  l. `4 n<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
. {& s0 s. ]( _& g4 s5 V) a" f  G<h3 id="二一对一查询">二、一对一查询</h3>
6 ?  ~8 O; A# ^( A: D<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
! u, f5 F  Y5 r: w9 s' h1 \/ V# V# W<h4 id="一查询单条记录">(一)查询单条记录</h4>9 L) o' p4 J/ e( f) a* Z
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>) p; t- s# b) @- u
<h5 id="1示例代码">1、示例代码</h5>
. Q. Q. ~1 h, K! @* j$ E5 Z% T<pre><code class="language-java">/**
2 ?( {0 y2 u6 P9 @ * 查询单个学生信息(一个学生对应一个部门)
% l) E( K7 F. i7 d2 Q2 h" \ */
  V: \. r. t+ a, T7 s1 X8 Mpublic UserVo getOneUser(Integer userId) {
3 x9 a" x/ J- O6 Z/ p# X    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
5 R7 A5 }% b8 X0 b        .eq(User::getUserId, userId);+ T( s4 s7 a1 M7 q
    // 先查询用户信息  `6 @3 r. P3 C7 e5 A
    User user = userMapper.selectOne(wrapper);
7 Z4 K" o) U' Q8 e; E& e    // 转化为Vo
# L. t! l2 E. ?# c    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
7 m$ O9 E9 f/ a    // 从其它表查询信息再封装到Vo
8 c: _/ ^' b6 Z. f    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);: G1 h2 b+ w& a: y6 q  c  L# c! Q
    return userVo;
# g+ Q% |' u- f}$ H& F# F3 E3 n, `! B' Q4 L
</code></pre>, G2 [! F) g0 _0 f
<p>附属表信息补充</p>
. X' W; K2 B/ S; b<pre><code class="language-java">/**! x3 b& H& ^9 k+ k# c6 U" \' _
* 补充部门名称信息6 X. ]% C1 C8 E2 ^
*/
( p5 t  _% B% F) S* sprivate void addDetpNameInfo(UserVo userVo) {
( {( U; i# w  Y" \; n    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class), l# }& {6 k: Y' s7 y: l
        .eq(Dept::getDeptId, userVo.getDeptId());
  f, E& l7 ^5 \  u, W8 @3 f    Dept dept = deptMapper.selectOne(wrapper);, w7 W" i9 Y5 g1 M$ a
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
. u  D" i8 Y# d3 x" ]4 E/ V' C}
+ c# o) l. t! M" }# _) X6 X</code></pre>6 V$ m# @* ~- t( Q, s  S& E1 d/ s9 l
<h5 id="2理论分析">2、理论分析</h5>
. i; G! W9 q% v4 O+ ?<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
6 e$ ]& G* o, K4 A8 B. |6 O<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>  H1 ^8 E1 f2 B& J' W8 \5 r
<h4 id="二查询多条记录">(二)查询多条记录</h4>
' g. e! d$ X) W3 S  y+ X4 u) R<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>0 i/ Q1 j5 l( S
<h5 id="1示例代码-1">1、示例代码</h5>- C+ Z: ~4 O0 _. s8 a  z; q
<pre><code class="language-java">/**# l2 ^( G6 `$ |2 r
* 批量查询学生信息(一个学生对应一个部门)
. }5 Z! F5 U3 ^$ U: R */1 `8 @. l) b, c$ B4 J$ M
public List&lt;UserVo&gt; getUserByList() {! h. m, Z' q- l3 q. q! O" l
    // 先查询用户信息(表现形式为列表)
1 }9 O" m. O$ Y5 u& a$ [% K    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());/ R4 Y; l* o5 v+ ^8 i3 k
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
$ D" C8 f5 y9 y. }/ E! ]    // 此步骤可以有多个  ~) @" ]' N8 o
    addDeptNameInfo(userVos);* q+ V/ u  U8 I
    return userVos;: S3 y7 R# G3 H/ @& e
}' }7 E6 i: u7 X( p# f) h
</code></pre>/ s  T7 V/ u4 R1 N0 ]8 S
<p>附属信息补充</p>* U2 o* J5 M% U& V
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {
$ R1 z/ x( O# ^, k$ O4 k; }    // 提取用户userId,方便批量查询
4 k! y) f4 V0 x0 D" M+ H    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());) W0 a0 v1 t3 |& g3 f! P, t4 f
    // 根据deptId查询deptName(查询前,先做非空判断)' [+ k5 T, I! Z
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
8 A7 k8 P9 |" Z2 |    // 构造映射关系,方便匹配deptId与deptName6 g/ ~* C& G, s
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
6 I5 P$ w- u+ H+ l" {    // 封装Vo,并添加到集合中(关键内容)# e% W% P$ \+ F; ~8 z6 {
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));7 S) U/ H5 j. t1 p) t4 }+ ~
}
8 Z( F2 e$ T! I+ c2 J% V4 A</code></pre>- }7 q6 a4 v$ f0 E3 p
<h5 id="2理论分析-1">2、理论分析</h5>
* D- n! t6 @& a/ }+ B<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>& I5 C- X7 S5 d& r6 ?; U' c/ D
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>; D5 l7 Y9 A: I1 u1 a
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
0 V8 A) m2 [$ M+ |& g7 k+ J<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>' x  f* s( O' R6 M+ A, u
<h5 id="1示例代码-2">1、示例代码</h5>: r# r: k2 f7 h/ N/ M
<pre><code class="language-java">/**
( @  G" Y" E, E$ j! X * 分页查询学生信息(一个学生对应一个部门)7 p0 m2 {& t+ D+ M
*/
" H7 v1 W8 Q) Epublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {- g0 v3 Y( T5 B( u9 N/ g; S
    // 先查询用户信息7 k) ^1 G/ |5 t& g' C! |( i
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());# B! n9 O; H# |2 M% w8 F- ~
    // 初始化Vo
7 E" D( I- X$ o    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
4 f/ K: \2 Q" f, t: j    if (userVoPage.getRecords().size() &gt; 0) {% m; C( {) I; Y, S/ d5 e+ k1 A
        addDeptNameInfo(userVoPage);3 U, u* ~2 u% d" d
    }
' m0 `) l- [9 n8 ]    return userVoPage;
+ J9 n0 h4 Q4 ^1 N. G, c5 P}9 R& G3 [0 q, H% {- l4 m
</code></pre>2 o  k' U& q: _# {
<p>查询补充信息</p>' }4 D0 Z" V6 r1 a
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {: l, v8 j0 v# ^: p( M- t
    // 提取用户userId,方便批量查询  s: n2 D9 T  \- w5 ^
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
' r6 X4 X" ^3 e5 f- \- G  T5 f/ ]    // 根据deptId查询deptName
7 p: l' ^5 J; X0 O% a! C1 W    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
/ Y5 w5 {* r/ ^    // 构造映射关系,方便匹配deptId与deptName8 O+ O* s) t7 K+ ^' ^: d) I& Y
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));5 S+ ?/ n% ^7 ^! o% P
    // 将查询补充的信息添加到Vo中4 H5 |3 y# R4 S% ~5 Z( q
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
1 U0 l) ^8 J1 D" U& ^! ^}
; y4 q; `% d) ^  v! S</code></pre>
2 o) x( f; K5 r; F<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
7 J9 z& Y9 V% Y, b8 I& b9 O2 h<h5 id="2理论分析-2">2、理论分析</h5># g# F0 }4 b( `
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>0 o: t5 X- \+ H! |% t
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
$ x( A% J4 h5 S<h3 id="三一对多查询">三、一对多查询</h3>
& K2 N* U* S( T+ Q4 @<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
* ^( q2 P9 T1 n) |. `6 W<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
6 p5 T. `' [3 I; E<h5 id="1示例代码-3">1、示例代码</h5>
, C4 G5 A( t3 e<pre><code class="language-java">/**
2 p2 ]( ]0 _  E% u2 g1 s * 查询单个部门(其中一个部门有多个用户)
$ S" u# A, q& _: Z# l, O */2 i) L% J+ h! {
public DeptVo getOneDept(Integer deptId) {' ^; g9 \2 D3 X& Y- i5 _
    // 查询部门基础信息; [( c, W( \$ m% W2 q
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
# ^0 [: N/ ?9 q/ P5 T6 _    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
% W' V$ K3 O. H    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);; H( b- M; N1 Q  Y& I
    return deptVo;5 s" F' ~/ o% k' k( Z( K+ e
}1 f2 z: ~' a5 y- v  ~5 z& Y
</code></pre>
8 n. l# F" k6 ^; S! P) i1 W% h<p>补充附加信息</p>
4 X5 K$ b8 U6 q) u<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {; h/ r( h! ]# C" p
    // 根据部门deptId查询学生列表
' K/ W8 \$ w  N4 m; d    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());7 [2 ~$ \' E; G& G  u
    List&lt;User&gt; users = userMapper.selectList(wrapper);
( I" C7 S1 o; B( c( t/ I* r    deptVo.setUsers(users);) S! [5 W. {" h: n, k& j
}
5 s6 ?+ h3 h; W0 R; |2 @2 p</code></pre>
4 A. t* c: m6 y. O+ C$ g<h5 id="2理论分析-3">2、理论分析</h5>
5 J% N3 V- r+ s5 \" H<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>9 c8 i& o, v4 _, p8 E! s; B) v
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
" ]6 [% B: y4 n<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
, S' a& a% O# r" [<h5 id="1示例代码-4">1、示例代码</h5>
8 R3 D2 J( \; Q1 z8 _5 C' j<pre><code class="language-java">/**# S! V; v6 a! d& |. _2 f5 Z; y% a
* 查询多个部门(其中一个部门有多个用户), k9 Q, `0 c8 E% H# X, l* E
*/
4 q/ p/ v% ~& N/ M! M+ @" f4 b8 \public List&lt;DeptVo&gt; getDeptByList() {
; S- {# J7 C- Z8 \    // 按条件查询部门信息
# _% \/ M9 B$ F/ W& e    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
0 ^1 a9 s  H: B    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
: r$ y+ m& i5 K9 t    if (deptVos.size() &gt; 0) {9 ?% k8 @7 O& t
        addUserInfo(deptVos);8 |# J+ X" D( W& u( d1 R( }8 g
    }  Z; d0 _- s& `) d6 P. b' n9 ^! T  x# y
    return deptVos;/ O* V7 N% x+ Y1 P1 |2 L
}
; i9 A0 [" D" m- e</code></pre>  M) `) V! B  E( l0 n7 O# ^5 T! K
<p>补充附加信息</p>5 Y/ s4 K  q8 k8 K8 L& n
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
+ H8 I- S' U% A" G! A2 h    // 准备deptId方便批量查询用户信息+ O: s' U6 H1 {
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
2 f0 {! s2 r4 k+ `- |    // 用批量deptId查询用户信息! x. M7 K' T6 o7 ?4 P8 \- k
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));4 x5 @( D! F: U- d& h* a# a7 B
    // 重点:将用户按照deptId分组6 g. C5 z! ~9 N/ }/ w! n* @. P3 v
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));* K. f0 o/ N+ b$ ^
    // 合并结果,构造Vo,添加集合列表
+ m; }0 f' L3 o( g7 s% d    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
1 t0 L( b; f; f( P4 q}5 ?9 h, y' p" q+ D& c
</code></pre>" }' g# E8 l, A& V6 N6 x. |8 V
<h5 id="2理论分析-4">2、理论分析</h5>- n$ f6 [2 y  q- ?
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>5 q% ^- f0 u+ J5 |. J
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>) r7 s: V. {! h7 n6 p- z' A
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
' O2 J# F" D! S+ w2 e! T<h5 id="1示例代码-5">1、示例代码</h5>+ a$ `" ]' y  {9 N* G2 L, u5 R
<pre><code class="language-java">/**
! G* K1 }3 T6 ^; o& r& J( @7 q( J, g * 分页查询部门信息(其中一个部门有多个用户)$ |- j1 I* i" ?7 d8 B3 F/ J5 A
*/' X  H7 C/ G- m! p2 {2 P
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
" W  a& S9 J, g7 P    // 按条件查询部门信息
3 |$ H+ O; o0 D4 _1 Y9 Z    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());) B  d1 i5 {; L4 o; x
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
8 i; F% T) [+ z( `* L    if (deptVoPage.getRecords().size() &gt; 0) {3 X2 V6 Q! z  C2 Z  J3 U
        addUserInfo(deptVoPage);4 O. f9 [  e6 }0 H) z/ V7 h. v) B
    }
6 {( R0 l  ~; j  y! h    return deptVoPage;
" |' h2 C5 R: g$ b) J5 n}
) ?& j3 [4 i* \$ i</code></pre>* w; F& T- u4 B3 }: f
<p>查询补充信息</p>
7 U; V- B' }. Y, z  w) n6 t! _<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
# L/ |( ^; t7 C: N9 [    // 准备deptId方便批量查询用户信息
0 }* q- o/ w/ o1 Q    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
  Y, o3 r9 t4 \, D4 V  O    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
: E. h. M# H6 Q& U8 k/ D5 r    // 用批量deptId查询用户信息
1 U; J2 k5 T. L' o    List&lt;User&gt; users = userMapper.selectList(wrapper);7 A' X6 x2 x" Z- o2 z( `' a" ?
    // 重点:将用户按照deptId分组4 D7 s0 w$ j) [# x9 Y
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
0 P" A; w9 O1 n% L% ^: C    // 合并结果,构造Vo,添加集合列表# k, r" M+ g# g. {% _$ w
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
2 f# W$ J/ N3 i7 B$ H* H}
! l* Y# k& p% p1 j4 N, w3 R</code></pre>
3 O& ?, x, f4 A" L( P: f<h5 id="2理论分析-5">2、理论分析</h5>
! i; Z9 P# B+ P4 ^$ q<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
+ x  N4 V: Q+ ~# f6 }0 l; S<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
! v( |7 f: W6 G! L& N<h3 id="四多对多查询">四、多对多查询</h3>
5 Z. T3 V- t1 M* t6 A  X6 L/ t<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
0 y7 v6 p1 s+ ~0 J<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>9 |6 V8 l1 \6 H4 J
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>& F. w* J1 l3 L" O6 n  ^0 S
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >! L8 U+ b/ o' m  @7 b- q+ N/ `- t
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>. \0 K. s- c: E6 G# O' K
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>3 y  R1 b' X! T5 U% @- R
<h5 id="1示例代码-6">1、示例代码</h5>- |9 L& E/ Z5 t
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
* J. Y4 y# L; m8 |9 D  C) j6 C" q    // 通过主键查询学生信息3 s: ]8 g+ _' }5 q
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
6 I: I# y+ i& S1 Q1 @- y    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);/ c* {- i- P" V" I! l
    // 查询匹配关系
' c7 p) ^9 A3 F4 d* p3 [- K    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);8 R* P4 C8 u* P0 A1 f; j0 N2 W
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
) g7 @! D7 {( ~' t( I: J, ~# c    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
! Q. H  T- Y* _) _2 ~- u        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));4 A( d/ x/ v, y' Z
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
# B- |5 W+ W1 v2 c1 E8 L        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
7 }0 n& z; I* @; s$ r7 n& o1 n        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
. ]2 ~& U5 x3 e- ]3 M        studentVo.setSubList(subBoList);" _; x  f7 [! p. H* C! ^% l! A# @3 \1 t$ S
    }  x8 m* z% Y# ?. R4 ?
    return studentVo;* b  Q. E+ ]9 ~% g0 [) p6 u
}
2 w% E- q+ |! `1 V% q</code></pre>6 F* w; }/ v& U3 z& n
<h5 id="2理论分析-6">2、理论分析</h5>& q& ], y# m& G8 }8 I( V, i
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>& q8 v- L) n% W  U. s
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
5 ]! M7 P* }" G. B9 {<h5 id="1示例代码-7">1、示例代码</h5>9 K4 R" e5 y" ~( D4 `
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
' k8 [4 p7 \" [$ a& P# T8 v& `    // 通过主键查询学生信息8 h4 \) x% k! `0 ^8 a# B" }( ]9 k) m
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);' h* [" ]; y4 N$ K1 m* ^
    // 批量查询学生ID
4 h5 R/ ?$ T% J- h7 j, t- R' O4 i    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
0 n. `$ k) Z* I2 h' I1 N- T7 I    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);+ M8 |0 b, A. N, `, G
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);4 P. I6 L# o# d6 [* y$ Q1 A
    // 批量查询课程ID
( f! d1 ]$ G& j; n    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
/ r, \5 B! B- f! h    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
3 n* P, y. q2 k* k% y  ^. K: c        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
# W# f1 g; \' E- s) w: T        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));* m) d- n" k3 W% h* f
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);" b2 a: _6 i) O" R
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
' J$ B7 }. h, }; ^        for (StudentVo studentVo : studentVoList) {9 }% a7 V% p0 i. |, h! i* A! ~$ _9 t
            // 获取课程列表7 q' }3 y# k$ k7 r, m2 e
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));2 F5 L9 x4 ^- y3 U* j& Q1 V
            // 填充分数
8 A: ]0 N& L5 t4 i# J3 Q. m            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));8 s4 N' ~  l9 R. y4 L9 R
            studentVo.setSubList(list);
' f, `0 }* n# @, \: ^        }
0 `9 W% \2 Z& n+ J1 Y5 k    }# H3 S$ O/ t2 U. _3 O! @0 u
    return studentVoList;; c# O4 q2 T  y$ _# U
}
6 B. k! l& D) E$ }; y  A</code></pre>/ F* [+ X; b+ @: |8 T( x& I) p
<h5 id="2理论分析-7">2、理论分析</h5>! x/ s& M+ B! X
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>- g# s# i- s$ x# ^  O
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
. P. ~$ q0 L* G8 f6 z# h<h5 id="1示例代码-8">1、示例代码</h5>" A; [5 Q2 z; D: a
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {3 o  ?1 H/ Q- D2 a5 H( n# Y# ?
    // 通过主键查询学生信息
% ]) D8 c' T. U" C- Y# p. R    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
/ q3 v) n( G0 q) i8 g; o$ @- L7 \    // 批量查询学生ID  m  _4 H0 h3 n* A  O/ S' P: y0 l7 `
    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
8 R9 m. t8 n, q2 l* P    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);  S  o4 @( t/ Q: F# B% J- A. q# H
    // 通过学生ID查询课程分数+ \8 C" A8 ?( v* D2 s
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);/ m" G% i) o# v- \7 E7 Y: Y
    // 批量查询课程ID) `9 \/ l  g5 o! n% ^
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());; g( v. R2 G4 f
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
! w" M) U1 a, N- u! x        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
+ j; M8 ^. n2 |4 c& i/ k7 I        // 学生ID查询课程ID组- p0 d$ e  l; _+ g, D* B+ V7 N
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
1 Q* I" j2 [  Q) b- l$ K, y; f$ ~( H5 v
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));7 l' M& H+ r6 @/ N4 k
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
, L' V* v% J* t8 Z% p& B7 G        for (StudentVo studentVo : studentVoPage.getRecords()) {
" J3 ]8 c' A, k2 ^) x7 {            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));# ]8 x/ k4 E  Q9 ^- H4 i& g
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
( W+ n$ |) I1 [- [: m            studentVo.setSubList(list);
- \' g( ~0 I/ X        }  ?/ [+ H7 ]1 ~/ p7 i# Z
    }
  l' |8 t7 F/ P7 Y/ y    return studentVoPage;
+ g8 y- G  v* F' p8 q; @. `4 A/ o! g}7 P( F, m+ C! ?) x( g  k
</code></pre>
: s, B- L9 N0 C' l: M" X% A8 \<h5 id="2理论分析-8">2、理论分析</h5>
- Q, O+ Z1 Z0 }- M& b3 ^" n<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
+ p4 g6 Q/ X+ R% Y7 \<h3 id="五总结与拓展">五、总结与拓展</h3>1 @. n8 M3 k4 X$ J3 n; v
<h4 id="一总结">(一)总结</h4>
: v9 O! U" ~/ L6 V! V8 S* H<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p># Z* p) h8 a7 x7 Q! {
<ul>
5 E, b9 J0 d3 l( h8 d9 U3 v<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
. v* L3 P% [& a8 B$ [) `, Q. S8 I<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
, Y, t; q) M. t$ K$ L<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
( }! P3 O& E: _8 h3 H4 e+ [5 ^7 k</ul>0 r% Z. v- ]4 v
<h4 id="二拓展">(二)拓展</h4>3 P; O0 |* i. [7 y% \* ?7 [
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>- }8 }* s7 ?& j- d
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>( z$ R) d; `* Y' o* a
<ul>
. S( O  o+ o4 c% D<li>当数据量较大时,仍然具有稳定的查询效率</li>
. O0 {$ H/ r7 U</ul>
$ S* w3 i' `0 T1 ~; s<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
3 G! `3 }. y: C8 _, _# ]<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
5 t: N  ?: t) F3 c, ~<ul>. }: @; a/ _3 O6 M- _5 G4 W# v8 m
<li>与二级缓存配合使用进一步提高查询效率</li>" x/ Y6 a- b/ q5 X5 q- t
</ul>
9 W; z% W% D, b* @<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>! x" e0 \" P0 q$ Q: B/ d% T# t
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
# X( F- q- j9 B1 b+ E, H+ d* B, }$ G# ?8 f) V
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-6-29 18:15 , Processed in 0.066759 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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