飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8240

主题

8328

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

' G  k6 E" ~+ {, ~; Y<h3 id="一序言">一、序言</h3>
! j/ i4 O& X' s$ @<h4 id="一背景内容">(一)背景内容</h4>
1 v2 G9 w5 ]/ ~+ ~<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>
7 ~3 }  J; l& u8 Z% N  K2 f) L4 i<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
2 y7 J! k/ `4 ]5 _% g: R0 d. ]$ e1 ^<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
0 p' J" S9 q8 v<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>$ i8 Q5 v+ n' q: B0 G5 f+ P% v
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >- n1 m3 F  D4 W/ w
<h4 id="二场景说明">(二)场景说明</h4>
0 b$ P' X, u, |7 n5 \+ t<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
. r" Z- o0 `; f. d/ f# _<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
0 C! P" k+ l8 O1 F# Q- Y<h4 id="三前期准备">(三)前期准备</h4>
& [* q; F" r, V3 B# X* v<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>9 E  \/ u6 w# I. u* J- f
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >, a# Y- T6 K% D# w3 q5 L$ D5 e4 H
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
0 D2 t1 h# @. n<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
' z4 v* i- q% q+ G+ F3 K+ F<h3 id="二一对一查询">二、一对一查询</h3>) X9 G! c9 D! z% F. x
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>( a# u* w2 \# n' p
<h4 id="一查询单条记录">(一)查询单条记录</h4>3 h# {! F( x+ ?% n; `
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>7 |8 c0 J4 V# x$ y- F
<h5 id="1示例代码">1、示例代码</h5>
0 v9 R8 _) c( h<pre><code class="language-java">/**
; N! d1 O, Z( I7 Q * 查询单个学生信息(一个学生对应一个部门)
4 }7 [( A5 i4 U- g' o# j */
- a" s" M' [4 G5 C  U. P* xpublic UserVo getOneUser(Integer userId) {
4 J" }$ [& G" ]6 ~, _4 h    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
. _; B3 O# @+ G1 x3 l: [$ C& }2 u        .eq(User::getUserId, userId);4 |6 W. E' R! D2 |' u% K' a
    // 先查询用户信息: ?& V) n: v; t" k/ H2 A/ A2 e
    User user = userMapper.selectOne(wrapper);: O0 Q: A/ h1 {! h$ J
    // 转化为Vo5 F( S( X8 }8 y/ v1 S. J
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
6 D& p3 j& X$ j& \8 C    // 从其它表查询信息再封装到Vo( j2 H4 [. l+ j6 n& E
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
: z5 z, O5 H+ |$ M' w" p    return userVo;; F! _8 e( Y6 k
}( o3 ?6 J0 x% m6 d, F6 N
</code></pre>9 }  h/ D# y% N) L! d1 K8 K
<p>附属表信息补充</p>* j1 l, q9 h" U: a* H
<pre><code class="language-java">/**( t9 e& g# K7 F) ~/ {8 ^
* 补充部门名称信息
/ [- I+ F8 t  E# r. x, B */5 E) u; [4 t$ ^1 e
private void addDetpNameInfo(UserVo userVo) {5 @2 k1 C# [9 I7 N% D8 ^8 Z; E
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
  z2 l& j5 z* ^        .eq(Dept::getDeptId, userVo.getDeptId());
, E% i7 C/ {4 \$ w    Dept dept = deptMapper.selectOne(wrapper);
; e) n9 s) ^; {0 V8 d) G  i3 F    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));1 u7 J" q5 E( q5 x/ a& _
}1 N4 w' r( {4 d7 Z. m) A
</code></pre>+ p. l* l' n9 F2 \* n8 P. c/ [8 C) C
<h5 id="2理论分析">2、理论分析</h5>  j. G1 L3 V0 G" Y* t$ _  V
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>0 ]5 B; [2 ]" x) g% U. n
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>8 y2 ^! K8 o$ I0 ~
<h4 id="二查询多条记录">(二)查询多条记录</h4>  Q& k$ ~7 O) D8 l2 b  z
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>( T' T; F' H4 G7 O( H
<h5 id="1示例代码-1">1、示例代码</h5>
/ F% x# T( d* B' u6 N: j<pre><code class="language-java">/**6 {1 G7 v8 {7 l! R  b! E; ~$ F# P5 ]
* 批量查询学生信息(一个学生对应一个部门)
. b9 n7 q, Z. Y/ ~9 T7 A */
* F" v/ ]( C( ?- d$ P9 x/ bpublic List&lt;UserVo&gt; getUserByList() {
  S% l5 z" r, Y* q    // 先查询用户信息(表现形式为列表)6 H3 P, ?' y6 O5 |2 {
    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());
. ^0 Y5 _' A; s  O: }( V    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
3 j' d$ Q' [/ U3 O* D+ r% ~    // 此步骤可以有多个2 {  h7 \0 W. X8 x+ d3 H
    addDeptNameInfo(userVos);5 t# D# c' {) U2 J8 @4 w# z
    return userVos;
3 y3 l: M8 g( k$ B( T' Z}3 ]/ m( m% m- Y0 l% \  n7 E% B/ F
</code></pre>
/ Q, e2 Y" [4 }( S. \0 i<p>附属信息补充</p>+ A4 @# T& B( H  Z" b9 c- l
<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {% b$ s! S+ a# _0 h
    // 提取用户userId,方便批量查询+ o/ a6 P4 _6 d& K0 Q# u
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
0 F: E0 k1 D/ Q    // 根据deptId查询deptName(查询前,先做非空判断)+ X8 V# m! ?9 P& C9 k' g5 e
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
/ a3 O+ h4 p+ j" Q5 }+ A    // 构造映射关系,方便匹配deptId与deptName
  I: A: _0 I& H( e, y; X  t4 g  c    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
) g$ J; N% V3 `  t1 `) L9 n. ~, B) z    // 封装Vo,并添加到集合中(关键内容)  D9 z# u* ~* }
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));$ C  U8 i* _, v( J0 \0 L1 ^+ [+ r
}. }! Y- ~/ c/ W0 _3 D) ^8 j& E2 `
</code></pre>) a9 C0 w9 X6 {* N$ L5 }8 O
<h5 id="2理论分析-1">2、理论分析</h5>% |, }/ F3 k* c9 ^5 O
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
  `- h( v6 O* Z" C<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>0 o- ], p5 u  I' W; t4 q
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
3 H% Q5 t- G- O<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>
4 z! {  T% m5 q" ^/ |7 D<h5 id="1示例代码-2">1、示例代码</h5>& G' l5 }$ L4 g  m( M8 F6 b3 d
<pre><code class="language-java">/**
- L. C. D# w& o  y * 分页查询学生信息(一个学生对应一个部门)" a5 k3 A; [' f9 u7 e' i
*/6 A  I1 U% E& o, v1 }5 H
public IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
/ h" u$ Z  n% M# y3 J' g( e    // 先查询用户信息& I5 _: Z  C7 f+ c- k0 h2 v! q
    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());) @: B  u7 @# j2 t
    // 初始化Vo
1 k" u8 F9 n8 b& ?6 o" s    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);. I4 x4 G% b; x
    if (userVoPage.getRecords().size() &gt; 0) {4 i" U& b5 B; d! l/ O) q
        addDeptNameInfo(userVoPage);; x. A: f) g1 H
    }
. z8 r8 g& V9 `) Q+ o    return userVoPage;
. n: Q" B, \- c7 D}4 r  T- `. R) t8 j# {7 t
</code></pre>
. O# |) L1 u9 Y2 a$ s# G( A  ~<p>查询补充信息</p>
8 _0 _) V2 a0 a4 ]0 {  L- r0 c<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {, ]! z1 G- U, m! n4 n0 p% Q
    // 提取用户userId,方便批量查询( I/ O8 g+ U# F* S8 R5 Q
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());5 p5 t* Q2 r  z
    // 根据deptId查询deptName
6 D' b2 ?# [+ X  \  m7 T: b    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));  H, W* I: u7 s1 w) v; R' `, o: r
    // 构造映射关系,方便匹配deptId与deptName
  b; h. G' v% H* w    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));6 n! e5 T; k* a
    // 将查询补充的信息添加到Vo中
7 H6 c- g7 q" O! }7 F9 G7 t    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
* f+ g; \2 }7 h: @1 e}
' ?7 q  X8 L: t2 ?</code></pre>
+ x! e. H" I$ x6 p. @2 H8 c2 N<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>
& R+ n1 z- i% f% F2 [5 g<h5 id="2理论分析-2">2、理论分析</h5>
% H6 [' t8 p( k/ _* n<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>/ T. d1 H( Y) V+ y
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>2 r3 n# e  W! L4 r, j6 \
<h3 id="三一对多查询">三、一对多查询</h3>" u6 O4 a8 u9 n- z* X1 @
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>' k6 A' S( X5 D% v1 `$ y5 V
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
& }6 F2 j' }; F, g8 Q3 f<h5 id="1示例代码-3">1、示例代码</h5>
0 _5 ?3 Z" ^% j9 l' q8 T7 P<pre><code class="language-java">/**8 I9 [2 I( Y* L' V& }8 M7 X
* 查询单个部门(其中一个部门有多个用户)
7 Z$ U4 ]# I0 |, x- [ */  V( L  Z$ y! D: F: w% Y
public DeptVo getOneDept(Integer deptId) {
' z0 @+ P; r$ A, n3 F  x7 _    // 查询部门基础信息
" N! b0 E' W5 P% I9 h% p8 A    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);# W7 J( e, _4 E
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
) h; [' U! M- c8 \' t    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
9 ]5 _( N) r( Y$ x5 \9 ~    return deptVo;
. v4 J2 w0 W* W' }  k}
# [0 z& B0 a' V2 n</code></pre>
) G  w  L+ R$ Q6 S) q6 o" {" A<p>补充附加信息</p>
$ F' o5 y/ |* T<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
. E+ Z. l7 H! D7 N    // 根据部门deptId查询学生列表
. j! j" i3 g& x2 J& W! ?    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
! R( c) H8 O2 o+ a/ l3 w$ m3 K    List&lt;User&gt; users = userMapper.selectList(wrapper);
+ t  B! C- R: y* L    deptVo.setUsers(users);( [( g0 ^2 I. v0 q- K1 s4 @* h7 Y: V
}  C5 {9 Q. O4 ?- G9 ~
</code></pre>
" B/ m5 J# B8 v<h5 id="2理论分析-3">2、理论分析</h5>
& y+ ?2 p" i$ o% w* X+ y/ U/ {<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>3 l0 L' U1 g0 }, Q3 n
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>8 N& F* H0 {3 Y  ^- B9 e0 G, P
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
  v8 ~4 |7 r0 z# w/ n8 X7 E( `<h5 id="1示例代码-4">1、示例代码</h5>) L2 u2 P6 t( Z' \2 W1 A# P
<pre><code class="language-java">/**
$ a& ?9 R, @* V% t3 D; ~  v * 查询多个部门(其中一个部门有多个用户)
! F* E/ p5 l5 O  i4 ?& E6 }/ ~5 i */
7 o' ]; K3 h3 t3 L. B3 `public List&lt;DeptVo&gt; getDeptByList() {
" Z8 o( J  g1 n# f) v1 L    // 按条件查询部门信息
* ^" w! P7 |! h* P% y    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());- l& M2 b) [/ a4 Q) \
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
6 K4 Q7 e, P8 P5 K  m1 G( X3 {    if (deptVos.size() &gt; 0) {& _5 X& \2 i3 J& F- h4 v: x  G! @
        addUserInfo(deptVos);
5 E) Z1 t' ]5 o3 u  A    }
7 R' T! l* t5 n, [$ O0 f    return deptVos;
. C4 u' I0 n2 i- y* R$ J; S6 X}* D5 i% k4 a) S$ A* u& g. Q
</code></pre>4 Y2 {$ N1 O, Z# m
<p>补充附加信息</p>
' W1 n& H8 A  B' H9 F<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
8 }+ W: _# i8 {    // 准备deptId方便批量查询用户信息
0 r! J& A% o0 b  R! I8 D% _0 p    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
  s6 p9 N+ i* @) s& J    // 用批量deptId查询用户信息& A8 s" j& b9 P; A3 @  ^
    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
2 U0 M$ W" _; `: b6 P( o    // 重点:将用户按照deptId分组
: n" V+ C! Y( V4 E- P( N" L) |6 }    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));7 \7 K! ?; Q- P, y8 z) c# L
    // 合并结果,构造Vo,添加集合列表. k# |. t- w3 n
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
9 y4 v' n/ d3 b2 c. v}
0 e' x) s8 [# o! o% |% x% q5 c</code></pre>
" Q3 `" v0 E) q3 m2 x+ ]. k2 H) Q<h5 id="2理论分析-4">2、理论分析</h5>
% d: ^* D' S8 z9 S& S% V<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>. J- ~6 ]3 M9 f$ V2 Q" x0 J
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
( ~4 K+ S& Y# m; T; D3 h3 g& i6 \0 ]<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>& I# S6 S8 X8 U4 v' }% B
<h5 id="1示例代码-5">1、示例代码</h5>
6 x9 i9 `, `$ B/ W" b/ O+ P<pre><code class="language-java">/**
! n/ M6 N+ \! s9 b * 分页查询部门信息(其中一个部门有多个用户)
/ N$ s+ q2 D1 I0 L8 M% L) C */
* }4 Q8 P' B7 epublic IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
: t/ p% s! E. }7 ~    // 按条件查询部门信息$ @( \) \. W) H! K
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());& \4 F- c# @5 s0 d
    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);0 @3 @4 o0 y1 X
    if (deptVoPage.getRecords().size() &gt; 0) {
: w+ q& {) e( T# Y        addUserInfo(deptVoPage);
2 N6 q0 T) l6 L# p/ s% s' A    }
8 W# W% P3 X9 o    return deptVoPage;6 [" s) h, A3 ?5 M+ i+ b% ^
}. y3 \9 @; Q+ Q( M7 Z3 P
</code></pre>
8 m* Z5 X. _# p% n* k<p>查询补充信息</p>
4 S( f% S5 Y# t* m<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {. w5 a/ y. H3 X& U7 j! w0 Q
    // 准备deptId方便批量查询用户信息
' y1 ?1 A$ r% _4 S% |! b: a3 R    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());
. i) O* J, u. ]& g    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
& }. x8 u; }; U+ h3 V; f    // 用批量deptId查询用户信息7 ~" [- U0 Q+ o+ {
    List&lt;User&gt; users = userMapper.selectList(wrapper);4 I, C( a6 T& J, A6 ]
    // 重点:将用户按照deptId分组
4 s* x4 P. [* x) n    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
; c6 {7 M' A9 K6 t    // 合并结果,构造Vo,添加集合列表
2 }# N; C( o0 `3 D! m    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));7 Q  J9 Q( W$ V/ ?% F6 K  X
}$ `" I4 W2 w8 `7 a' {
</code></pre>% [! k. H# y) R7 P6 w7 G1 B1 k
<h5 id="2理论分析-5">2、理论分析</h5>
2 S+ j4 F" A9 W<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
* i. ~: j9 b! g- L, Z1 E/ M: m1 D) ~<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
* |4 Z8 Y- C1 R9 H1 G6 m) Z<h3 id="四多对多查询">四、多对多查询</h3>6 f8 j0 _# t) h% U* x3 G
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
+ b, q  j; [: p" W* h<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>% n# m' Z" u5 s: |
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
3 l( S, [: A& ^* U4 i5 E5 m<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >2 Z% j. Y) l3 Q3 g) L" k% V  S9 F1 h  Z
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
# r4 f; v1 c) F5 B<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>/ E; v* Z3 V0 u6 o& P  T
<h5 id="1示例代码-6">1、示例代码</h5>4 K, q2 h- p6 G/ Z  U3 X( X# m, D1 j
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {3 `. V- W) ^; t- b9 [  e- l
    // 通过主键查询学生信息* z6 w/ F2 W- y) a0 N
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
. _& k. u, h% W+ J    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);* T8 R+ Y1 @, s8 o, ~
    // 查询匹配关系$ v3 V1 R6 k9 C% Y% G# E, p# {* |
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
1 |" u& D( b* w5 h    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
$ x. ~# o/ U0 F! U& c    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {; N' K# }7 T  N/ N  H$ U
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
; n6 p) @9 d5 T5 U8 |        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);& m' r8 J( a4 q9 G
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
5 s8 |& x3 V" O' b$ l9 Q( ]4 E% R        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
# L3 o! |& A' J4 J! [        studentVo.setSubList(subBoList);; K7 Y. I; S0 U5 ]$ ?
    }
+ ^  E  V9 b2 N    return studentVo;: _; M9 U# b9 t5 l" c8 v7 _
}
) {# ]/ A! S4 F3 a4 Z: W</code></pre>
* k2 z: t, F( Z<h5 id="2理论分析-6">2、理论分析</h5>
/ Y  s* E8 T- P, X. b. n+ s' Y<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
3 G" L8 D1 `7 d<h4 id="二查询多条记录-2">(二)查询多条记录</h4>) s7 k9 t  t- s% E
<h5 id="1示例代码-7">1、示例代码</h5>+ P0 ^- D0 n/ x% e+ w+ l$ h
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {8 l) P; V, W: I
    // 通过主键查询学生信息6 w+ F7 ?* K! D. \
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
% Y  L( {; \" d, S! n3 U) E    // 批量查询学生ID9 W3 b/ G" n2 d1 g( ~' ~/ _
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
& \: H6 w, d# z    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);- z' g# j( C# s
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
9 ~# I! x6 `, ]$ w8 A6 U4 k    // 批量查询课程ID
. P1 H- A; C. Y9 r6 ~    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());$ r3 Z7 N$ m: ^8 q
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {/ {9 F8 L; Q0 n) B* u; A
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
3 j) H4 B! I: o( p4 u4 O        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));2 b& T+ H% q5 b3 v* K
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
9 E- `- X3 {8 d        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
7 U% A  @  ^$ a8 G$ O        for (StudentVo studentVo : studentVoList) {
  L6 ?8 V2 N$ x/ N0 q' f4 O% b            // 获取课程列表4 }* z5 h9 u" s$ }% W' ^0 {% H- I
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));4 D" p0 V, e, @# T) J6 D  i+ W; p
            // 填充分数
/ u* U7 x8 Y3 I/ r            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
/ y2 ~/ O. L' E; C0 K. B/ W            studentVo.setSubList(list);
* ]1 m" K% s- t" y% w        }
- n' z1 X& [- t. L' i    }
  e5 y' R8 l1 T% L  {    return studentVoList;+ J* V  P- Q6 H* o
}
2 S1 S5 `2 N, ~4 v</code></pre>
) a; K5 z0 F- t<h5 id="2理论分析-7">2、理论分析</h5>
' i8 L' h* M6 q1 v. U- d0 a7 M! k<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
- Y& E5 Z. t" R/ H/ m# p<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
1 H; _1 G* T- O6 u# d<h5 id="1示例代码-8">1、示例代码</h5>! X9 @: M6 Y9 O- ^3 }; {) m
<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
) @6 o5 i  e! U3 H. w( C$ i    // 通过主键查询学生信息
" T1 s: {; W; }1 Z3 f, N    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
$ y' y* `# K1 b1 b1 n- o- |    // 批量查询学生ID
) T! s. r6 ]/ u+ [/ _    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
5 i" N! H- e7 g5 L+ l( V4 ]    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
  s) ~5 B0 r: S$ ?1 X! L3 D, Q( d    // 通过学生ID查询课程分数+ c" g* F  |+ i
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
- w* ]- S2 j/ B! a" o0 A    // 批量查询课程ID6 m# V. C; S, g
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
/ m7 J2 r( {  \+ T6 a$ r" g    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
' W  T* A* I- c# G8 N* t        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);5 w! P% v4 a  g
        // 学生ID查询课程ID组* G' h  R$ N  n- j% }
        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));! @# q  ]6 M0 ]1 _$ F

4 _& a% L1 \6 J% h/ I% N        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
. u8 W. r6 H; @* w: _' e* q, a! m1 `        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);& y6 O5 i% X* C2 B/ ~
        for (StudentVo studentVo : studentVoPage.getRecords()) {
# l0 \# f; g& q' w6 x' G& H9 z            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
+ u8 V# b' E; n4 f0 B- V* G            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));3 R4 ]6 I  s6 U& B' B. ^( Y
            studentVo.setSubList(list);
! q1 }3 h/ i& ^! p  q        }0 v5 M7 e: r) c
    }
; O0 Q  L: p5 h) {% S. W: B    return studentVoPage;# _! p( J3 Q% I7 d+ l
}
2 C% Z4 s. t2 j# W! E, |) p</code></pre>
0 e. v( V7 E' B3 R& K* ^. S6 G0 H" y<h5 id="2理论分析-8">2、理论分析</h5>1 g' J) i, L' r8 z& v4 ~' t
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
9 r5 c2 ~; r9 z6 c<h3 id="五总结与拓展">五、总结与拓展</h3>3 L7 m$ P" |- k, [
<h4 id="一总结">(一)总结</h4>% J( ^2 F8 J7 `  @; ]
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
( q( o) F* E7 Q/ M, o9 f<ul>% d5 H9 h$ Q: G) p
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
* ?& L9 @( b8 p8 c0 O<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
# t1 p" J' N3 F1 h2 U<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
* e6 z- R. F0 e' f2 i</ul>7 v9 w3 Z$ e5 L  ?
<h4 id="二拓展">(二)拓展</h4>! J' ?; i2 T% E6 u; l8 U) {
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
6 m6 {% @; o/ M0 {) L<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>
/ ]  T, s: d2 n: [4 F5 ?9 t. o<ul>$ E( C0 u3 ?6 `- A1 {( k
<li>当数据量较大时,仍然具有稳定的查询效率</li>
6 T1 v5 ~; Z9 h: U4 |# }</ul>
" t4 b0 U' i; e- L4 D! M! K8 l<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>% {$ F) ^$ {5 \' x+ L2 B' i8 e  s
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>& X! }& X1 x/ J& c! Z8 e
<ul>; u; U) `6 V" \) O3 X9 i
<li>与二级缓存配合使用进一步提高查询效率</li>
4 Q, p! q7 T4 B, F, O</ul>
3 f: @! T$ u. G* i; F* v  u5 o# k<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
3 W2 V& n6 r( C1 f! F<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>; r, A- X. l; D

: p7 Y/ j* p# b- X% g
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-1-12 23:51 , Processed in 0.068957 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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