飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

4137

主题

4225

帖子

1万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

3 P+ l! k- I! M+ @  d8 x<h3 id="一序言">一、序言</h3>
( `/ F! f$ V6 J9 X. T) |<h4 id="一背景内容">(一)背景内容</h4>! x* M; {2 `3 N& Q  {: |- _
<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>1 k, r% W" i. I5 k0 n% r
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
- P5 m: ^' M7 W<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>  {. t& P- @$ M9 }  @9 c
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>7 B% p( i' t3 r  _7 y
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >8 \$ j2 [2 o# J. n' N9 ]2 M
<h4 id="二场景说明">(二)场景说明</h4>
# m# n' v' |5 V7 ?  x9 f$ @( s! B<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
8 l7 J$ L3 i2 E9 y1 M<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >% p" K0 O2 c" D# Q9 h; a8 o4 p
<h4 id="三前期准备">(三)前期准备</h4>
  B3 S( u- z7 Z, ]" B2 T4 m9 D1 ^6 t<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
' ~6 E, ?5 S) C7 A: Y<img src="https://www.altitude.xin/typora/image-20211021135113431.png" ># w% _* ~- G6 d1 Q" {' X% B
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
- P) D( C3 ]/ b* M<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
1 S6 ?2 @* v, D  s# W7 n<h3 id="二一对一查询">二、一对一查询</h3>
1 N9 D6 N- c- z<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>  R& L+ T/ k9 k
<h4 id="一查询单条记录">(一)查询单条记录</h4>1 e) x9 b: f3 p/ g. Y% ~
<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>6 s3 `# I4 k' j3 t0 J' l5 v
<h5 id="1示例代码">1、示例代码</h5>
0 k" h+ p/ p6 v  M9 j5 q' |<pre><code class="language-java">/**3 |) Q0 }! s& K& o& F4 n
* 查询单个学生信息(一个学生对应一个部门)" D- u: ^  l2 o2 F7 H+ ^
*/
' d' A- w' g3 z: A( ?- d! F( G9 n$ R) Npublic UserVo getOneUser(Integer userId) {% c) {( }6 t# e
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)) A3 H) ]" H% f( \, y( B- l* r# x
        .eq(User::getUserId, userId);/ c) t" C/ X, c' |  r* w! r
    // 先查询用户信息
' h/ P% G% y5 h% ?7 _    User user = userMapper.selectOne(wrapper);
, B9 G+ l" g9 G: e    // 转化为Vo
4 }6 q9 L# z: T% y8 c7 B2 ]    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
* f, {1 J) V  `  Z    // 从其它表查询信息再封装到Vo
& G/ x& O0 R$ Q$ y- K4 g& k% v    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);, c  a/ x& V* U/ {
    return userVo;
9 O) ?) Z% w: K+ V8 h& l}/ A  O! `8 ~; j
</code></pre>3 I+ E- |6 c: A! l* B5 F  |
<p>附属表信息补充</p>
# ]; x+ N. k. M2 P! \7 x<pre><code class="language-java">/**9 L; s- W$ P" u) H5 h
* 补充部门名称信息1 T* F# [" g# E! h) d* O
*// O0 Y8 o# E/ d- c0 q0 i
private void addDetpNameInfo(UserVo userVo) {
9 v* E( T& |, z, B4 e9 S% H    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)
+ J9 Z  A6 X1 v' v% @  S8 I        .eq(Dept::getDeptId, userVo.getDeptId());% k& w  |& Q. x
    Dept dept = deptMapper.selectOne(wrapper);' A1 ]; D% H5 _" \) U
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));
4 q( S+ i- H( R/ Y& n% J* k5 m% h}
/ u& a8 s# B. j7 {</code></pre>
# }9 O" s3 x5 @" Z: e<h5 id="2理论分析">2、理论分析</h5>
$ h  M9 {* n. d<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
* c# Q+ b$ L) O: t: S' C<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
# W0 {3 ]* o. h<h4 id="二查询多条记录">(二)查询多条记录</h4>' y% ?1 e) X$ h' l. }- O
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
8 Y8 w) W$ l' k# [* S7 m<h5 id="1示例代码-1">1、示例代码</h5>
/ w: C8 {5 z: B! R$ J  _<pre><code class="language-java">/**7 u2 \: Q& M! _
* 批量查询学生信息(一个学生对应一个部门)  j' |1 t+ e, D! J
*/
+ \8 j! x- ~1 e" U! apublic List&lt;UserVo&gt; getUserByList() {
' j# b9 A* U, @, h    // 先查询用户信息(表现形式为列表)
9 A2 R7 d# q0 w    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());6 ^5 Q3 z/ k5 Y" m! N5 j- l: f
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());! }, I( Y8 i( ]+ O( C
    // 此步骤可以有多个
7 y3 y, Y" D, b: x6 B' |    addDeptNameInfo(userVos);
1 a! o! j# a% J8 h+ o) y6 `3 T5 Q    return userVos;
0 W- h2 B4 }. p0 \! j}% r' `- [" N9 M' M+ L2 h1 C* G- M
</code></pre>
( t: r, s! J- @: {$ J, I& V2 Q<p>附属信息补充</p>
4 s7 Y0 U' S, w$ ^, N& P<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {
0 k8 O6 z' o2 ?* ?+ T6 U; X    // 提取用户userId,方便批量查询( N# T4 Z; ?% C, ~2 n
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());9 o! a) F" }% \# l
    // 根据deptId查询deptName(查询前,先做非空判断)
1 ]0 ~0 Y2 A5 u    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
8 w: `7 Q  _5 W4 Z' P    // 构造映射关系,方便匹配deptId与deptName
# L6 ^$ Q9 j7 ~    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
, X# C6 k0 |- g/ t6 n( u    // 封装Vo,并添加到集合中(关键内容)
/ m' r$ `" l6 R    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
: r* \8 p3 \$ T1 c8 K6 }: r- A}% ~& x  z  m, s) T2 t# M9 u" ?
</code></pre>" I5 D. j+ A: ~& N: M% C& J
<h5 id="2理论分析-1">2、理论分析</h5>
" w7 f- E/ z4 ]: O4 `<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
' v- c) J& R# e, v( t' A( ^# _7 B<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>& r1 h0 |" f& k3 j% L7 Y" |# d, Y
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>( J) m& O, u3 S( j, E/ P! ]
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>/ I5 ~. P- t( s8 G; k
<h5 id="1示例代码-2">1、示例代码</h5>7 D2 N4 K- i6 d( W
<pre><code class="language-java">/**: T  I1 s7 z7 g+ t- @: P- o
* 分页查询学生信息(一个学生对应一个部门). h7 W0 Q& u+ E& l  ]
*/
0 _/ v- x# F! ^  H; s! j4 H) Spublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
7 [- r3 T! V+ u6 K2 _, n* p    // 先查询用户信息
3 U) F, P3 b4 m, j    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
  S$ y8 U( v0 U/ i" n2 H    // 初始化Vo0 Q0 v* I& z7 G4 Z% U/ S5 P( [9 S
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);# @* _1 K' x, T! U' P  f
    if (userVoPage.getRecords().size() &gt; 0) {
/ C& t, e4 T2 e1 l7 c8 Z! w. Q        addDeptNameInfo(userVoPage);
+ P  X& V6 E7 u6 ^1 {5 H    }
- i. |1 N% t" d  j) S! P: K    return userVoPage;
& C; k: p- N; C! L}
; t% n; J' }( ^# z- q; {. [9 Z</code></pre>6 L' K' j5 t; `
<p>查询补充信息</p>$ \2 [4 N. a# O! Q. e/ n0 ^
<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
4 S: T) x! M& F' C' M    // 提取用户userId,方便批量查询  n0 g5 M, M$ l% c: i
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());/ ?' a. i2 [/ q) O7 O; s
    // 根据deptId查询deptName
* J, [; Y; `. B- r5 Y/ w3 g    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
5 H8 b* ~' o; c2 T1 c" |# P* R    // 构造映射关系,方便匹配deptId与deptName, N+ `' u! ^  ]8 h9 M8 ~" V6 ~0 e
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));2 K$ j0 a4 \/ g: E/ a* a& J& N
    // 将查询补充的信息添加到Vo中
  ?$ |4 t. M6 d' t2 j' k; l    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
1 M" ]. D. n% o9 `$ M}
, g8 u% W$ {5 l8 k  @' J- y</code></pre>1 `$ C2 D! G3 `  @
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>& h+ E) S/ O4 M3 w
<h5 id="2理论分析-2">2、理论分析</h5>4 G' M; \) ]* k1 d3 S- ]% O
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
& F; w$ |- h* }1 x+ Z<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
# o5 n* M  G8 p$ m<h3 id="三一对多查询">三、一对多查询</h3>
- R$ t3 c3 p  ~) F: {1 y; Z<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>5 a+ L# G0 i, P4 ?
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>) Q+ U1 n. J- c: e! J: t
<h5 id="1示例代码-3">1、示例代码</h5>4 d6 J2 h8 ^4 G2 K/ t* i9 S0 H
<pre><code class="language-java">/**
: M5 ^9 ~5 Z& W1 w5 y6 a( K * 查询单个部门(其中一个部门有多个用户)
, {# E" ~7 A' V  n% Y+ } */
1 S# U7 J4 ^  U# l, w, A$ v  ~public DeptVo getOneDept(Integer deptId) {, ~$ S. Y6 _3 d2 N9 L
    // 查询部门基础信息
& p2 P& d4 B0 ^6 X9 `' e9 F    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
1 r5 [1 g& M. L" Z/ Q    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
& Y! Y1 Y1 _5 c/ C0 U    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);/ a. {' K& F/ O# [8 `! l6 |
    return deptVo;3 ~( b- P' y0 e1 y. H
}
1 U4 ~2 B# C' g% ?$ b: W; P</code></pre>2 \. v2 f7 C5 Y
<p>补充附加信息</p>% V; j0 [$ a1 |" B9 H! S
<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {% U. N) ?0 ~4 r! H, D4 L
    // 根据部门deptId查询学生列表& M% {1 t3 A' w3 T
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());% ~$ G( ]$ y" c: E% Q1 v
    List&lt;User&gt; users = userMapper.selectList(wrapper);$ i$ v/ S1 p& X  _; Q7 `. e
    deptVo.setUsers(users);
$ z: O: g: o  f}% O  |0 k! ^2 I2 e+ E
</code></pre>) s8 `5 \9 p0 ^2 f/ x9 P& U
<h5 id="2理论分析-3">2、理论分析</h5>
/ X, c, N6 Q" n2 o$ ^# t<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>4 ^- P$ Z4 F7 C' [' v) h
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
! n) G! z" W8 d- M# M<h4 id="二查询多条记录-1">(二)查询多条记录</h4>/ X( e3 Q1 H0 f% a/ r' K
<h5 id="1示例代码-4">1、示例代码</h5>) @) L, z% e& z- Z" {) Z. V1 i
<pre><code class="language-java">/**. G- _0 P: K1 j3 ]7 A
* 查询多个部门(其中一个部门有多个用户)$ M7 ^  X0 V: x5 S' ?; t+ l# X
*/
# Y% ~# f, y% S7 B. C3 p* Epublic List&lt;DeptVo&gt; getDeptByList() {, k9 W( z& p  A* z8 z+ z. @$ _
    // 按条件查询部门信息2 V" u& A  S1 }# T) T
    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());) ~$ |  z/ B# W5 Y
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());; J+ T% w! s/ _% i
    if (deptVos.size() &gt; 0) {4 Z, q$ w9 p) Q3 T/ L# E/ Z0 r
        addUserInfo(deptVos);
# e. D/ g" D4 c; R    }
$ O+ S0 \) I3 B6 R+ s  r# ?    return deptVos;: I7 q) ?, [8 Q
}
9 X: i0 W3 T, k' R* t- ]3 j</code></pre>
1 Y2 A" v4 L7 n$ O! ~' c% T) T<p>补充附加信息</p>, Z2 T0 M/ H. T
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
6 b" t- I2 t2 p, L3 B& T% V    // 准备deptId方便批量查询用户信息9 D8 z* L* P2 n/ q- }" }
    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
# \1 ]' f& E7 Z6 K. u    // 用批量deptId查询用户信息
: ?( _7 P) P  c5 b* M2 R& @# ?    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));/ D- K# b4 q2 g! F  ]
    // 重点:将用户按照deptId分组
/ D. ~; V; C: T0 A1 n* r    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
3 H7 j. V- `, L) Z    // 合并结果,构造Vo,添加集合列表: S. Y3 g8 J3 W& Z4 x% ^8 I
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
8 a' N  P8 ^" J8 U( a- Q$ `}' m5 w. O" l; p: u9 |" J" ^$ ?
</code></pre>
# y7 }0 S# d- D& t' p& a) `% L<h5 id="2理论分析-4">2、理论分析</h5>
: @0 I" ]& N5 {3 v5 @, _<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
/ N2 i) g0 a9 M$ D1 x0 i' B: k3 E% h<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>! g  B! S1 V( }3 I
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
( K& I' \0 Q9 p$ f7 S<h5 id="1示例代码-5">1、示例代码</h5>
$ {/ ?5 j9 O( Q. h" U+ ]- B' d$ u<pre><code class="language-java">/**! ^; M  Y' X, A4 |
* 分页查询部门信息(其中一个部门有多个用户)
' q& ^+ G3 D7 l$ H) J. ] */
# N" [+ n* G; W( P/ H# ]  [5 P+ k( }public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {/ g* d6 n- l  r4 A
    // 按条件查询部门信息( R/ y' C6 t6 q
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
4 v/ _7 z1 w6 `# w& S    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
$ G$ K/ ~9 J: I* ?, X    if (deptVoPage.getRecords().size() &gt; 0) {
0 s$ E$ ?5 W. @        addUserInfo(deptVoPage);( ?5 w# l5 k) p/ ]& E" A$ ], x- R
    }8 b" v7 H' \8 _
    return deptVoPage;
7 l7 T' ?; z1 h7 n% Y2 ~: S7 n}4 S. v2 m* h$ U8 O7 |
</code></pre>
9 F+ C) q" C7 Y7 j; s, b2 _) ?<p>查询补充信息</p>
; X) I4 T5 a2 z6 C( \& u<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {  Y( m; ~& G/ i/ B# I
    // 准备deptId方便批量查询用户信息
8 a: E) U* n" J! f1 z( T    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());; J* M! ^0 ]0 i9 O
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);  \9 D8 p& x% ]. {/ r
    // 用批量deptId查询用户信息0 z* }' k. u! a
    List&lt;User&gt; users = userMapper.selectList(wrapper);: _: j3 E- r) a% ]: c' @
    // 重点:将用户按照deptId分组- E% \/ w: H1 e. w; o$ [6 L6 B
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));' v6 b$ S' ^3 L7 ~
    // 合并结果,构造Vo,添加集合列表
7 q( w4 n4 _) ~5 G& h    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));, U  y+ a6 t; _- q& q. s' v! `
}' Y" h5 L5 p: q+ t1 H2 c
</code></pre>
! h% ]* f4 b" F) C9 L3 g1 ^<h5 id="2理论分析-5">2、理论分析</h5>$ Y9 j' E" @' q$ O. t
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
! s" j8 p: o& z6 L( f8 m1 m<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>! S5 w% _! L+ A% [" r. j5 ^" G9 M1 X
<h3 id="四多对多查询">四、多对多查询</h3>
8 P/ C/ O# b8 w6 X/ l$ @<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>: |8 f7 c3 `; K0 O
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
: Y- o1 ]0 q" K<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
" m- b$ I* x  J5 U<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
' f) }9 v3 a& f/ |% p<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
' @" H5 v1 E! _/ G5 ^( _" A<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
6 U9 Y& t) D5 c% Z& Z( u8 I<h5 id="1示例代码-6">1、示例代码</h5>
; a  V( n9 @4 A8 m8 U<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {( ?) Z0 n; J" Z# M" C6 ^; m
    // 通过主键查询学生信息
7 ?6 G) d: \6 d; s; U    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);% y  X+ l# Q7 I: ~
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
. _" B4 l: _: @( y: i    // 查询匹配关系5 `: r0 S. M) l# S/ Q1 b) W& z
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);3 V0 O  d  ]6 i. P' j+ l
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
4 s$ X# B3 |3 P0 ~, u    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {( Q4 U6 j  j. {6 C6 W3 |; G
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
/ j% I' h8 U/ I4 W" ^1 q        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
0 E3 _6 ~- A/ Y        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
. Y) A0 |1 O+ |* ?        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));' f9 L. B& M) ~7 s2 f
        studentVo.setSubList(subBoList);5 M0 x( E2 b% |/ w: @' v
    }8 s# ?& H6 J! s! g2 y8 P
    return studentVo;
  v! @# j8 G  @5 s; a}2 ]! ^& j0 B8 h1 J0 r- \
</code></pre>
9 W/ G( N! Q" [: c6 z/ k<h5 id="2理论分析-6">2、理论分析</h5>
. n1 A$ J9 ]  C5 v" D+ j<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>  \2 \1 X: e& C7 X
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>9 p  m8 Z  W3 W0 {
<h5 id="1示例代码-7">1、示例代码</h5>
7 P- c5 J  M: d4 g2 w$ t8 Q" ]<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
! ^! M, o0 v5 t8 `    // 通过主键查询学生信息$ c. ^4 v1 _8 B, K1 k
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
9 K: q4 {# n5 [0 e: [    // 批量查询学生ID3 a: I0 e  Y0 f; }: }3 i# k
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());% X5 t  Z! z: K4 x
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
) |3 J# }4 @% _: e; |- A) m* x    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
6 A1 {. h. u. k6 a4 N    // 批量查询课程ID1 c7 G. s. D! z- C
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());$ q. |; A+ Y/ [. e* S  B9 G1 R
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
2 I  s& n6 a* S$ {. O( K, @        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
  _7 b" Y: o6 |        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
( L# N: D* ~7 t% R        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
5 e+ \! f- w$ \7 P) u# P" ]6 I        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
4 o, a/ S9 c+ [' A8 A; [/ `        for (StudentVo studentVo : studentVoList) {% T# O' a+ G. [5 S
            // 获取课程列表+ j& N. T' G' b' J: n2 S
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));9 o" X1 Q* t8 y' N" h! v: S! K
            // 填充分数& q2 M7 q6 T) L( e, r6 T3 `
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));; r# S& j3 t+ W2 X6 v4 \3 ~
            studentVo.setSubList(list);
2 f% q, e. S& K. q+ X2 p9 P        }7 T# f7 j0 X8 o) W) |0 S
    }
) A9 y( `4 A* Y  c2 r8 p. y, D    return studentVoList;
6 r/ Z: E0 T& t, F0 B}9 R! \( |& i- M
</code></pre>$ b; O$ m1 E" L  ^4 K
<h5 id="2理论分析-7">2、理论分析</h5>
% P/ h7 x2 y6 Q# R' @$ H2 b<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
1 u* p1 n# g8 Q<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
1 |* r& `# {* l5 r/ `7 _. C; M. P<h5 id="1示例代码-8">1、示例代码</h5>
9 _. T! j- T* \; t<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {+ z& F7 C& }* V' f6 V  Z6 I
    // 通过主键查询学生信息
" @) K* |) u/ p0 O( j    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
7 e7 [& o  K1 r' R    // 批量查询学生ID
$ w; c! O* n, i- X5 r* a' l    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());" ?: V1 J; q+ k
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
6 C0 I6 \* G- m    // 通过学生ID查询课程分数8 N. R  S) N! u! e5 z+ l
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);4 `0 t& E; a7 h' U6 |, S* H. Z/ O
    // 批量查询课程ID  w4 o4 n& Y% R
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());5 X' _6 i8 i; f& |! ?. |0 i! r' V! `
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {# S: ]) ^( Z6 c8 }0 D
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
! j* a; t, A2 w' j' T8 ^        // 学生ID查询课程ID组
! m5 X- W7 `. _' C        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));! d! ^; O7 z  [# \
. u3 S6 [9 `' m
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
: k0 e. Z' V, f        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
& W' Y" J/ T- }! o        for (StudentVo studentVo : studentVoPage.getRecords()) {) H/ ]  ~1 [5 L5 @) y9 m
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
; `$ E, c/ E  T! L            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));3 X; G; c/ X; V  `
            studentVo.setSubList(list);1 [8 J8 E2 b( H8 D. M$ R5 _
        }8 S. t/ }3 _) y# c0 L$ w
    }
4 i' @, V( V" X1 f* w/ U# A6 |. a- r    return studentVoPage;% ?" J) y3 q0 V  U/ Z. P
}; L4 ~. X# L! e6 _2 g
</code></pre>- v' Z- T$ ^9 |
<h5 id="2理论分析-8">2、理论分析</h5>
+ {8 H: i8 ~) _9 V<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
) y/ l! ?/ S- M$ C7 F9 l<h3 id="五总结与拓展">五、总结与拓展</h3>2 V8 w( U2 I; J
<h4 id="一总结">(一)总结</h4>
- H6 r' x. ~* w" _2 T<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>6 B  ?: E: g, j
<ul>
+ A! i4 A. @+ D: d<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>. [' x& |- b) M! z4 _6 a
<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
" n  S6 F# }; b<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>: f# G+ k% C  n1 j3 i
</ul>
5 s! Y+ c. r+ O$ _7 M. X  l<h4 id="二拓展">(二)拓展</h4>
$ o) z( V) h6 t" @5 Q<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>$ k% F8 w4 E, H. x4 N
<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>* O+ {% ]! |7 g' h
<ul>
- r2 U- [1 ?& l( y( N, [) w<li>当数据量较大时,仍然具有稳定的查询效率</li>" J& W9 @" f( u. U8 D, e
</ul>+ x# G+ g2 e/ D9 ^# J5 i0 ^
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>( |8 G4 ?$ z2 @/ \' l( Y0 J2 z# M
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>, X) |) |/ p1 e+ n
<ul>
( q1 e$ z! E' l4 i8 U) x  F$ X<li>与二级缓存配合使用进一步提高查询效率</li>
; N1 n% B7 @- M$ Q! H6 Z" D</ul>$ F, J* S& v4 ^, C
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>. d6 A7 |1 h1 u  V+ w+ g
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>* z8 p& L) d" H1 }/ B6 x

; Y0 M! v1 D& f9 j- o8 W6 C3 U
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2024-4-25 08:32 , Processed in 0.064518 second(s), 21 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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