飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8135

主题

8223

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
26735
发表于 2022-2-12 14:35:42 | 显示全部楼层 |阅读模式
2 U) M+ i: g! N8 @6 d5 D' o: k
<h3 id="一序言">一、序言</h3>4 ]2 I) a$ r* H& b) i
<h4 id="一背景内容">(一)背景内容</h4>
4 H3 c/ `- `+ `2 T& p! ]; ~<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>+ J% v: Z# {( S2 x( D- d  e
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>
' \8 p3 l# v! B4 p8 [/ z6 s* g<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>( U5 R9 _9 ?) ]6 t2 y4 r6 B: Y& k
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>$ D* G8 K" V! Z# t% o
<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
4 [& s' h* z" F$ t! z. Y# h' [<h4 id="二场景说明">(二)场景说明</h4>
" X; W8 }' c% i7 L! m# G<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
( c% ?- h9 ]7 w2 i<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >6 B, z9 d+ \2 ]0 p/ s1 J" g
<h4 id="三前期准备">(三)前期准备</h4>8 {) {: i5 X2 V+ B
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>2 C9 u( s4 i6 [* ~, ^! e- o
<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >
5 r' Q0 L6 D4 v0 x<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>* ]4 ]- q- {. ~- ~
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
* W+ B! ~& l' L0 Z<h3 id="二一对一查询">二、一对一查询</h3>
) S: V- X4 _0 g<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>
: P" Y: d( `6 b0 _( O' B<h4 id="一查询单条记录">(一)查询单条记录</h4>
' ~9 s+ w% Z2 `* m<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
) P) J, B! b0 G6 w/ o5 Q0 x2 ^<h5 id="1示例代码">1、示例代码</h5>
. {% c3 |" c1 {# n; z/ r<pre><code class="language-java">/**
6 h% ?. X4 T+ e, B: J3 C, z1 U * 查询单个学生信息(一个学生对应一个部门)
  @$ Z5 j$ ~  F* e+ ]1 M */7 f/ a/ e& ^5 l
public UserVo getOneUser(Integer userId) {
) b. P% |0 t; M  R5 y    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)2 A% F' b4 k; u
        .eq(User::getUserId, userId);
# [' v- d; E4 p0 ^7 S) X5 ]) Z7 m    // 先查询用户信息
7 C/ i; m* a; e    User user = userMapper.selectOne(wrapper);
& H/ s4 ]7 K5 o. e: E3 [9 d    // 转化为Vo2 b' N. t: j) r% t
    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
1 h8 C2 ~% d' ~+ z" C! c/ L    // 从其它表查询信息再封装到Vo1 `/ x, b- M& `
    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);6 g8 U' V& Y, P9 v4 n% I/ Y
    return userVo;3 l" E) e3 ]& X3 g
}
  h; {9 {  o" ], Z' |2 }, u</code></pre>1 h$ ~& I* S; W+ F9 I5 z8 d" D$ Q
<p>附属表信息补充</p>
# [1 K3 B0 t! b% @/ N<pre><code class="language-java">/**
: @; D; o( D( r1 \& ] * 补充部门名称信息
5 }/ ^* J( h6 `/ f& ~0 F9 i */
) Z4 O: T$ T2 |) W4 Tprivate void addDetpNameInfo(UserVo userVo) {
8 A' X# e, s  S    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class)+ x0 \7 C2 L0 t% ~- f0 o
        .eq(Dept::getDeptId, userVo.getDeptId());0 K% V4 ~9 S; O$ a
    Dept dept = deptMapper.selectOne(wrapper);4 t! x% }" r* I8 v$ M+ q2 M' c
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));5 Z$ \  r. U; o) N; @# I
}8 \. F$ n1 n% x3 b$ A: |7 _. S" Q
</code></pre>" A0 W( q8 i8 `3 r; l1 v. h+ J
<h5 id="2理论分析">2、理论分析</h5>) h5 c9 I; M* p' H( Y
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
7 ?, G: B( x7 k: r# v<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>1 c: j8 ^# N& R& }: T
<h4 id="二查询多条记录">(二)查询多条记录</h4>
: o# ^: {" l9 m) P' \$ M6 I; K; I<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>
% d/ c/ ~$ Z& I6 N) ^<h5 id="1示例代码-1">1、示例代码</h5>
6 |% H6 D  Y4 R<pre><code class="language-java">/**3 ^7 F$ _5 q' i) r* G2 z7 J* _/ K
* 批量查询学生信息(一个学生对应一个部门)
( k6 ]; N) D$ M2 B7 {! u. B */7 E/ p2 k+ b, K' n
public List&lt;UserVo&gt; getUserByList() {& H' R% F/ F* {
    // 先查询用户信息(表现形式为列表)
& q! h! i6 W# H' v2 ~5 J    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());7 y  Z5 z9 s7 ?  N# N7 |
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
9 u0 c1 K7 L6 A1 V4 H. L* H5 \5 W    // 此步骤可以有多个2 A3 T) J+ Y) w3 N0 ]) \/ U( Z, E
    addDeptNameInfo(userVos);2 \  Q1 A. s1 M, @
    return userVos;( q- v3 h. P7 l2 ]
}. ~" {3 U, Y1 K( R) Y7 m0 e
</code></pre>
) r) S( c! B' t<p>附属信息补充</p>
3 o' v/ _' W) c9 z* M/ u* P& W<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {
6 S! ^8 ?) F$ F/ K1 x4 U    // 提取用户userId,方便批量查询6 v7 M) V& V  C! T) [5 H0 N7 ?. L
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());7 O% Z1 f6 g( Y+ q- I
    // 根据deptId查询deptName(查询前,先做非空判断)0 T; e5 r6 @8 {$ V5 L. m8 x9 N
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
- G7 G' E$ Y) p8 h+ }2 }; M$ e; b( l    // 构造映射关系,方便匹配deptId与deptName. |7 M. Z) J5 s/ T$ Z
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
3 |1 K5 z- [) i* m$ x9 U    // 封装Vo,并添加到集合中(关键内容)
" |$ e! T1 [4 L& B" u- N2 u    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
( g& c. d* ^1 q8 M1 H  U# ?}
# {0 g7 S3 _0 R+ w# U</code></pre>8 f  S* A8 L+ N# T$ T
<h5 id="2理论分析-1">2、理论分析</h5>% ?$ O  I& F8 _1 G2 J, w2 t
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
4 P! \6 n2 s3 n<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>3 H! Z% a" g7 M6 ?: K( Z
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>$ B& j5 i2 i8 @9 T
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>9 ^6 k/ g5 G4 k0 O6 u3 l# P
<h5 id="1示例代码-2">1、示例代码</h5># p5 M4 U1 ~" g+ {* |
<pre><code class="language-java">/**- `6 t- H. ^# ^
* 分页查询学生信息(一个学生对应一个部门)
# q% S2 `' f! C7 w. o */
) R) O1 O; K6 y8 a( k9 qpublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {6 m, d% L: |0 y
    // 先查询用户信息
3 \7 v+ V$ o' f+ \7 g, x    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());, q& B& w$ f. e9 g0 G
    // 初始化Vo( K  z3 I, [6 y  ?. |
    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);& ?; Y. s& b- K6 E6 ^6 ~# Y9 H
    if (userVoPage.getRecords().size() &gt; 0) {5 q; w+ s$ t7 E
        addDeptNameInfo(userVoPage);
* P, Y. R0 X3 O" B! O0 Z0 o    }  G' p4 A! B. A& S/ \
    return userVoPage;# C( N% X2 }) ?7 t
}
; h+ t7 I; c  {. W( h9 C3 s7 e</code></pre>
, l& ?& r: g6 _6 r  V( {1 D<p>查询补充信息</p>
; a7 q# ], }7 Q6 C2 V<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {
  R; s! v" `* A    // 提取用户userId,方便批量查询
4 n! o+ G4 _1 v$ G' [    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());2 e! k: D" l) N3 c
    // 根据deptId查询deptName3 s% H8 w- s# b, m
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));8 }6 U, _, X6 C  x' @7 U
    // 构造映射关系,方便匹配deptId与deptName  h) \' D  |) r# ]2 x( o
    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));
" P; D# C2 b7 o/ L7 a# T7 N    // 将查询补充的信息添加到Vo中5 s/ w9 m! D! _$ b( n; A
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));6 m1 O4 D- D% H; @+ x/ K2 h
}& R2 {5 k0 h8 ~$ Q! g5 u
</code></pre>/ f- E' ~3 q  G+ [) U7 C. j
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>: e$ W5 ~7 {* E6 _* J! l
<h5 id="2理论分析-2">2、理论分析</h5>
- r7 |* W+ r: ]; d' x; H<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
$ c9 `8 s2 g& m; Q<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>
- t' f0 z; P  S' k<h3 id="三一对多查询">三、一对多查询</h3>
: v( h' V8 X. a# _<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
$ U9 S9 {( V2 |: G2 H<h4 id="一查询单条记录-1">(一)查询单条记录</h4>4 D; l4 p/ c0 b. i
<h5 id="1示例代码-3">1、示例代码</h5>
, u- F/ o; E( Q- g% _: Q<pre><code class="language-java">/**
& ?! Q; {. C, F4 T3 y" H% r * 查询单个部门(其中一个部门有多个用户)
- s2 O  H" d: D+ Y( r1 X) J2 h1 @ */5 R6 E  w; k0 L" k2 Q/ M! j1 h
public DeptVo getOneDept(Integer deptId) {/ p6 S/ q0 Q, |2 j" S# L
    // 查询部门基础信息
& A9 W6 o* k- k- K    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
, Z+ y0 s# r* U8 D; Y: {% R+ a    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
8 x) Y" [0 e% R    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);, `6 G7 V( c2 P' v( z
    return deptVo;* X5 I" y/ B. m
}
! k; h# n& W  c: G$ U! u8 N</code></pre>
4 A$ m2 z: j* D' `: `& D; @<p>补充附加信息</p>
5 e$ R- P( d  {  q% H<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {
( z3 Q$ x3 @' y) R/ r    // 根据部门deptId查询学生列表5 U6 D4 U7 }, {1 G8 @2 P
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
* l5 h% [/ P4 s" [  _    List&lt;User&gt; users = userMapper.selectList(wrapper);
" e9 ^, T4 @7 r* t3 v9 b    deptVo.setUsers(users);
) o) A8 J( B4 f% V$ @3 L' [, G. _}
" S6 f  H3 l% I3 u+ h</code></pre>
7 O" D4 F# L! c% u8 _: _# [<h5 id="2理论分析-3">2、理论分析</h5>
: i/ U) n* @. \' c: L<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>
1 o) o6 T0 y- j<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>2 {7 e7 {' C9 e3 T" a) m! C
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
: Z9 ^  r. V% u6 r: B4 X<h5 id="1示例代码-4">1、示例代码</h5>0 r4 }9 t- f2 [  A" x8 l
<pre><code class="language-java">/**8 P/ m9 o3 y4 O! J1 P! x- K
* 查询多个部门(其中一个部门有多个用户)! P1 ^4 u7 g' v0 L
*/
  G6 P: [4 K+ Q" wpublic List&lt;DeptVo&gt; getDeptByList() {
5 q( A$ B% Q+ }9 P6 Z1 {5 o/ B8 S    // 按条件查询部门信息
$ }& D  ~7 G1 T2 v2 }7 D$ w    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());
) L; p( O" q8 z1 w; ?2 |    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());- ?$ h" [3 c3 C9 t
    if (deptVos.size() &gt; 0) {
$ ]6 ]2 y2 U$ S) k. T) }" P; Z9 ^        addUserInfo(deptVos);3 Y7 k; P" q+ W0 v
    }
& P4 G3 o# v6 F; Q3 S/ U( l3 j    return deptVos;
5 }& ^- d9 _3 w* Z. E9 ?8 L}
1 |9 I/ |/ w- j7 l. n# s& G9 C  t</code></pre>" \+ j6 A7 g5 J
<p>补充附加信息</p>; O/ U( J7 B# g9 d
<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {5 l# x, O% j3 ]3 E2 U5 n* v
    // 准备deptId方便批量查询用户信息
1 p) P8 y6 T! a) a    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());
/ i4 [6 j5 ^  C6 K  v    // 用批量deptId查询用户信息
$ A4 D2 m; W$ K  b& m  I4 y    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));/ i8 j" g, R$ y4 R2 h# J/ |
    // 重点:将用户按照deptId分组9 C4 @( S- o! J4 v
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
5 A$ z2 ~) V& b. {5 e! T/ X! }    // 合并结果,构造Vo,添加集合列表% y' u' o) C/ x5 ^$ `
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));7 D9 l% a+ ~4 y  R  Y7 F% I
}3 M" B$ U- T' N  ~
</code></pre>
, K% `5 ]6 c& \4 Y<h5 id="2理论分析-4">2、理论分析</h5>3 C7 b( T  a9 d4 I
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>! o( T& E. I. D% J6 Y# b
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
% b9 F* u' k+ U6 J5 `<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
- K7 z% g0 }! Q4 U1 }/ t2 p<h5 id="1示例代码-5">1、示例代码</h5>
: G, w! V' w4 @9 Z<pre><code class="language-java">/**
: n" f/ R4 O! D# H6 v7 ^ * 分页查询部门信息(其中一个部门有多个用户)8 X, P; r6 D- @9 |& ?) _6 K
*/; ^- Q( x' n1 I& X+ F2 M6 u
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {  Q! ^! l5 L, b
    // 按条件查询部门信息$ _; O; B7 T2 m$ |
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
2 \& P1 B0 j2 M) o    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);8 T, v2 b" Z6 a! }( v
    if (deptVoPage.getRecords().size() &gt; 0) {; z" j/ _, |* K8 z( q. G. @
        addUserInfo(deptVoPage);
& D- A  l5 ?4 |    }: ]+ ?" r8 ~* N8 ?" f" ^6 N
    return deptVoPage;
+ m. y+ I- x7 r}/ z$ g. K8 g0 o" S
</code></pre>* }2 K+ r& F1 H6 {5 ?( P! x
<p>查询补充信息</p>
) a" x+ _  ~, }, Q<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
# L+ l( c: ]6 B2 o% E9 ]    // 准备deptId方便批量查询用户信息
& q* ^6 V, e' y* D0 ?' t; }    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());5 c0 H4 V* E6 r1 y. ^6 _7 Y/ w$ v
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
2 b! ?: Z) {, U% `    // 用批量deptId查询用户信息$ d5 s" ?" g5 V& }# f3 V9 I
    List&lt;User&gt; users = userMapper.selectList(wrapper);
1 T. P+ }* x0 \1 n4 F/ S1 E+ a    // 重点:将用户按照deptId分组; h6 g  s; k' ]+ @/ I
    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));; K- A; @: F" }# j* b
    // 合并结果,构造Vo,添加集合列表0 x1 ^4 V+ W; U( K2 b4 P% Y
    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));0 u+ A0 Y7 m$ W3 s% o9 c
}  P  ^/ X, Q; r; \
</code></pre>  S  p7 |2 p+ X$ }+ v' @% x1 _& a
<h5 id="2理论分析-5">2、理论分析</h5>, X9 X; ~( n- X, V1 M
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>% Z5 M' O! D- Y% }& _& M9 q
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
% T9 K" D. G5 e, {$ ]7 O( Z6 y5 \<h3 id="四多对多查询">四、多对多查询</h3>" p. W" F$ g' a* @' ~8 U
<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>1 d7 |! ^7 \" ~
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>* D* O' k& I/ t2 v4 {/ |7 l5 S
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>! R5 J2 [1 H: r5 n
<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >
$ H5 M) z; e) U+ n# }: k6 i3 p; A<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
+ ?* @3 g& N6 c9 P( F+ s<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>
4 z1 n0 p+ p! y% ?- B* o<h5 id="1示例代码-6">1、示例代码</h5>$ h" i1 ^5 A  u( F& y2 r: J
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
. N9 }2 S9 C) `) Q    // 通过主键查询学生信息6 T. X! {9 q5 v+ ]5 \: r. l9 ?7 w: Z
    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);. j9 c; c* ~' X+ v3 l3 |3 C  U0 `/ u* ~
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);# Q8 M# i, X4 Q. ?, n6 y' L
    // 查询匹配关系
/ z2 y. F) i1 c- I6 T6 \- K. S    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);  E4 Q$ B6 V) S" x' H9 n( C
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());5 s3 M+ i5 r" a6 Y+ s% b) M9 {- k* ?
    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {  a  e$ z6 q2 _( ]+ R9 f! F, P- s
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
/ L6 {3 e) T7 \+ b: l# D( _        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
% }6 L3 {% T! R) y$ C        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);- ~* F. o6 c9 c4 g7 I( S" E3 Y
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));
) k5 x8 t2 M$ q  Y: c        studentVo.setSubList(subBoList);0 u+ n( w7 s1 D; p
    }4 |, k7 y6 [& f3 ^1 `% u% `5 j) i
    return studentVo;$ w0 ~, b1 u/ h- @1 w/ R$ g
}
) z& p7 v+ p0 N</code></pre>
/ e' t9 Q% H" Z9 M' a( O0 u<h5 id="2理论分析-6">2、理论分析</h5>: n( Q& [; N, }( i. l
<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
7 ^6 s7 ?9 y6 S# ~* n<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
. J8 S. J2 b: S) s; p0 t<h5 id="1示例代码-7">1、示例代码</h5>% F5 E8 L. f  Z  s: K5 F$ |/ c
<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {' K& C8 [+ a) L7 [3 R' M$ A4 I
    // 通过主键查询学生信息
7 {/ J  A8 p0 S+ \& g: A5 E0 e# \    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
2 y+ o1 s8 T# E- P" G    // 批量查询学生ID
: O+ ?, P* P7 E8 v    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());% H4 ?& e* _9 D3 M2 h( O
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);7 c' R+ d3 L6 N5 q1 R5 {
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);6 P1 A. g( J4 q
    // 批量查询课程ID
& a7 J0 O2 g3 G    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());% u* e6 o3 z2 ~, p$ y. m5 V" H$ e- q
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {: p# r0 h0 D% |' S  F' B9 x
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);8 s5 W' t, d( e8 n# Q
        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
$ w; b% J1 o4 G* W1 G) d" v- T1 O, W        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
4 Z; p6 |! w$ K( T# G; L1 W        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
8 ]" G: o' K, S4 d        for (StudentVo studentVo : studentVoList) {
, ]; D3 j9 T1 [8 d2 C            // 获取课程列表( p* @5 Y$ M! v, O; i
            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));
* m7 {  R' ]$ H# j& Y1 ^            // 填充分数
( k( y1 ]$ C8 v/ r            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));% C6 M$ y& L. v' q
            studentVo.setSubList(list);) n, j# N$ T3 g# n- N
        }
7 U1 Q6 s6 F& S8 k  k6 c    }9 W9 P% t1 m. |4 C9 @
    return studentVoList;
4 n1 G) M1 P0 V$ P. L' E}' R7 N- @: n# v7 q
</code></pre>
" k3 `  l% w' Y<h5 id="2理论分析-7">2、理论分析</h5>! `6 W% `$ \  g8 W- l3 q: |. @
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
% j3 {: Z* U3 Y4 k& I$ z<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>
( Z& i( e3 j) g' _/ Q- F5 A8 m<h5 id="1示例代码-8">1、示例代码</h5>
6 P0 d( u  c; q<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
! ]/ D- ^6 h& [; g5 {7 b& K; F    // 通过主键查询学生信息% X& i/ h" X& \3 _
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);& Q6 ?4 _. H/ K
    // 批量查询学生ID
* F- B/ i# d7 C! Z1 a- g' W    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());1 s" S, C. }+ R! _" e
    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);" L" \# o: @4 r3 }2 e
    // 通过学生ID查询课程分数) S$ |* T( t* O7 W2 O
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);+ ]6 c7 H; j. O; w
    // 批量查询课程ID+ Y1 U' p! p% d0 b  J
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
: ?( m* R, H1 v! ]" |5 O1 n    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {
" ?2 Y1 S, ~" G7 I/ J) G* ?        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
' _  x! R: I0 o, w8 C6 {        // 学生ID查询课程ID组
) U2 A2 Y0 N' y8 T6 i) A2 u' U/ k        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));9 F" j% o+ b! F0 w' i

% e8 R/ \; i( N        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));& N8 v' H2 u, s, I5 {4 S' o
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
# N3 Y! v# O1 U! F% k% A( B5 s        for (StudentVo studentVo : studentVoPage.getRecords()) {/ V' C) @3 e. i% b; v$ W
            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));5 \2 r% ?' ~' X
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));
4 X! L# p, s0 G$ ?            studentVo.setSubList(list);
5 h& W# C/ w$ E, I  A, A        }7 m" `! ~+ N6 e( o7 N
    }
1 o- ^8 Q) ]3 X5 W    return studentVoPage;
% }( W# u9 m2 c& e+ [! B% ]0 E}( p) y* a0 v0 I4 w
</code></pre>
- z( [! Z+ X" z1 q3 M) X<h5 id="2理论分析-8">2、理论分析</h5>0 ?; F, K  ?% H% r
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>' g4 ~/ \8 L/ D
<h3 id="五总结与拓展">五、总结与拓展</h3>
  v7 [2 U% q1 D. M! R2 W<h4 id="一总结">(一)总结</h4>9 r& ]8 L2 E  ~7 L/ N5 I' B) S
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>" @; e1 u' L* i0 s
<ul>
$ q( ?- n8 i3 `7 {. p* s<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
( D9 Z' T! g* x$ p<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
4 z  r! ~9 W7 P6 u9 e<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>4 ~! t4 m0 g. i% i
</ul>
- B* n! O4 _$ h; f5 h  F" V<h4 id="二拓展">(二)拓展</h4>
5 [' o7 o/ u% z6 |: B<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
& D/ _1 n- K) ^<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>5 n# @2 h% v. x. _3 O( q5 X0 ]2 t
<ul>
8 Y. t+ [: A  F7 T<li>当数据量较大时,仍然具有稳定的查询效率</li>
% J2 C0 `1 }* S1 T</ul>/ `+ O0 Q) @  U4 m# {7 \" _  }
<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
" C  f3 Z6 L0 H! J+ o2 U7 V<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>
  Q* N& T6 N" W, o" U2 T9 Z- \4 v! Z<ul>
1 E+ W; j, {5 o- J5 y' S<li>与二级缓存配合使用进一步提高查询效率</li>
$ l# f! |- q) S( q3 j</ul>& [* S( e/ t8 S) N; T$ F
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
+ W: `- Y3 ], r" q<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>3 G. u5 u3 Y& S  K+ C
; ]& K* T6 b: e2 B& Z- a* V% S
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2026-1-3 00:51 , Processed in 0.068226 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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