飞雪团队

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

MybatisPlus多表连接查询

[复制链接]

8058

主题

8146

帖子

2万

积分

管理员

Rank: 9Rank: 9Rank: 9

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

5 ~$ G- G1 H( ]7 W<h3 id="一序言">一、序言</h3>& o! ~8 G. f5 n
<h4 id="一背景内容">(一)背景内容</h4>
- Z/ _( H% M; H  i' a& D<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>! Q8 z5 O3 ?3 a( n9 ]' q" l
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>+ ^& D% X: H& g  U, f- u( |. h7 T
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>
; I' _! k* m- {9 [; A* E; m% G<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
) S  B, B) L' D) X& H<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >: N2 X- b# D4 B5 M, b+ e. n: ~
<h4 id="二场景说明">(二)场景说明</h4>
" c. o7 o4 _9 N" v+ l/ V  z% o. R) n8 F<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>
. u# J( H% l2 z7 J5 |' l<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >& i/ M5 k( T, q& X# G8 A, p, x6 U6 [
<h4 id="三前期准备">(三)前期准备</h4>7 O( E/ |  P' r! g: m' j
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
5 w* V0 d$ F+ E7 j) v5 P- o! I<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >7 C$ F# \: j# }0 `% `4 H2 X, W
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>
5 H* W/ n2 q# w3 E3 r' B# h<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>
8 U  d, X' F0 f' D<h3 id="二一对一查询">二、一对一查询</h3>4 `9 D. E4 D4 y
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>( a0 w3 {- f6 Y. n- ~; s: M: ~
<h4 id="一查询单条记录">(一)查询单条记录</h4>
7 U3 ^, ^$ A' }<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
* ?* X  W% Y' m2 Q0 v, I3 t<h5 id="1示例代码">1、示例代码</h5>
' \" A3 h( F& H  R$ C2 l8 k) K+ \<pre><code class="language-java">/**
  [4 B. j9 w0 z) @) e& a- t3 x * 查询单个学生信息(一个学生对应一个部门)
4 C* ~! a7 k7 M! o5 v4 c* k */3 Q) B, \% U) k1 q/ I) W8 v! {" r
public UserVo getOneUser(Integer userId) {
: {0 g3 B+ {  V- k    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class)
' I, H( y+ s7 K4 t: j9 x+ I+ l        .eq(User::getUserId, userId);/ }) e2 @4 R+ F' r# ?
    // 先查询用户信息0 o7 L+ W- |/ K0 D2 `
    User user = userMapper.selectOne(wrapper);
( e' g" {- A1 p    // 转化为Vo
$ {# D- V% D# [/ L+ @. u    UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);7 j5 |+ L! y. k) M5 x  q7 F% X
    // 从其它表查询信息再封装到Vo
  z/ k% v3 A0 t7 `! z( B, Q0 @0 _    Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);
6 W% }+ ^6 K+ k+ O2 u4 d" j$ `    return userVo;
, K4 m6 E! c3 ]! a& y}
* l$ s2 D' ~% K4 \</code></pre>
" y) y- P$ h3 d/ B<p>附属表信息补充</p>9 y+ _8 y% Z! M
<pre><code class="language-java">/**1 w( E! u# V) {# N% r) P
* 补充部门名称信息# T- P8 L! Z- f$ H7 R  A
*/
0 ~# K9 ?& k* L3 F/ u- Wprivate void addDetpNameInfo(UserVo userVo) {% R$ J- @9 N, R( g# i% N
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class): a3 R" b  i- f
        .eq(Dept::getDeptId, userVo.getDeptId());# E6 b, n* r- _4 c: i
    Dept dept = deptMapper.selectOne(wrapper);- j: o' N- A( l9 G: F6 W% q6 V1 r
    Optional.ofNullable(dept).ifPresent(e -&gt; userVo.setDeptName(e.getDeptName()));/ |7 [* o% @5 v, ?$ G% c& g3 l
}6 }+ N. D) X7 o7 ]' D
</code></pre>
# c: k/ X- N" T- Q<h5 id="2理论分析">2、理论分析</h5>, i' f8 a6 o" J# @* i7 w
<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p>
7 |4 c& @# M$ w! X" U5 L, b' J<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>
" |; U0 D2 _5 [3 y& W2 c& Q# V. o) h<h4 id="二查询多条记录">(二)查询多条记录</h4># ~3 t: Z6 V9 R6 Z' ]% \6 s/ D
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>( r4 }' E5 L+ l# W  R( g
<h5 id="1示例代码-1">1、示例代码</h5>
5 K5 n2 `" \- k; x, g2 K<pre><code class="language-java">/**
' q) G$ D: S  j! Y * 批量查询学生信息(一个学生对应一个部门)9 O" F$ @% @* F1 q+ S2 t! s
*/  v/ E5 n! ]- G. D
public List&lt;UserVo&gt; getUserByList() {
! R+ N4 Q) P& d! J5 M* V7 b    // 先查询用户信息(表现形式为列表)
: q- i! {: S: q2 A    List&lt;User&gt; user = userMapper.selectList(Wrappers.emptyWrapper());6 i3 a6 b& ~" R: R& Q" w7 @
    List&lt;UserVo&gt; userVos = user.stream().map(UserVo::new).collect(toList());
8 }. N2 R( d. V* \+ Q" T) J7 M    // 此步骤可以有多个$ u: e9 s( O3 S, o
    addDeptNameInfo(userVos);
, {/ R& m' R) y+ j. q: D1 `    return userVos;) D: E1 G' P# Y! P& g8 `
}0 U' ^4 q& \1 |& W. n$ M
</code></pre>' B- ~$ u3 {$ p, K% K8 K8 A1 Q/ K
<p>附属信息补充</p>
' ^! c9 o! w/ X, a/ @) c<pre><code class="language-java">private void addDeptNameInfo(List&lt;UserVo&gt; userVos) {9 c/ V% N# H: R& q* o2 @
    // 提取用户userId,方便批量查询6 r( @( r( n5 U0 F9 \
    Set&lt;Integer&gt; deptIds = userVos.stream().map(User::getDeptId).collect(toSet());
% W7 O* [$ g' f8 [    // 根据deptId查询deptName(查询前,先做非空判断)7 O4 I  [5 z) R7 o! a8 {( j( \
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));: S; V+ y/ y: j0 r0 L! _
    // 构造映射关系,方便匹配deptId与deptName
. s7 x% @2 Z! n" ~  S0 o% I5 q    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));/ W: }8 \3 d- N2 ~+ @
    // 封装Vo,并添加到集合中(关键内容)- t/ {- J8 G- _1 C* Q* P, v
    userVos.forEach(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));
. l. M' H0 p& a  r2 I}2 V0 N: p) w  R# ~
</code></pre>
5 O- ^$ e  k" [7 T) p  j$ H# \<h5 id="2理论分析-1">2、理论分析</h5>' t/ Z1 v2 d9 k- j
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>5 x+ g( E2 T- ]$ h
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>$ |( \( `) @3 U
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>5 B; E, [+ x! r& M6 r+ V2 ~& `3 A
<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>4 |- s* c+ T1 L: `$ X  i
<h5 id="1示例代码-2">1、示例代码</h5>
  P4 l7 F" S# M2 u9 N- Q<pre><code class="language-java">/**/ X) _: F, D: ^4 A3 a2 L" `2 o  E
* 分页查询学生信息(一个学生对应一个部门)4 T1 D; ~8 b3 H2 R& o% @
*/
9 }- y/ X' k, {9 t! Dpublic IPage&lt;UserVo&gt; getUserByPage(Page&lt;User&gt; page) {
$ n  D: E' i5 ?  K7 R    // 先查询用户信息
- U' V3 m' r$ \% K7 ?    IPage&lt;User&gt; xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());
7 E6 u  `0 [% |/ B3 G    // 初始化Vo
/ S9 j6 p- W: |5 q6 N9 S! v    IPage&lt;UserVo&gt; userVoPage = xUserPage.convert(UserVo::new);
8 u2 u* O$ D* K& k: a2 S    if (userVoPage.getRecords().size() &gt; 0) {
+ x4 Q" i9 L" m- P7 C, Z        addDeptNameInfo(userVoPage);+ ]* s" w! ~- i2 G! T7 \  k
    }+ D% U# j- Y/ S/ X
    return userVoPage;9 \3 u( m8 z& h& k
}
4 D* S, j2 L: \</code></pre>8 M+ ~% d! {0 d5 y
<p>查询补充信息</p>
/ s" i$ W3 ^; O<pre><code class="language-java">private void addDeptNameInfo(IPage&lt;UserVo&gt; userVoPage) {! W1 q$ _6 \, T; A
    // 提取用户userId,方便批量查询' I1 x  P( E2 `" ?  ~  t
    Set&lt;Integer&gt; deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());
4 |' x$ ~6 E' N* O    // 根据deptId查询deptName8 u6 ?# L  h( m& e8 ~
    List&lt;Dept&gt; dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
8 Z6 o% S5 D% D, e    // 构造映射关系,方便匹配deptId与deptName
2 V9 T% p  x$ C) c( j    Map&lt;Integer, String&gt; hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));* a+ \# H/ O3 i( F/ e% O
    // 将查询补充的信息添加到Vo中! k. \' {! [+ r  Z
    userVoPage.convert(e -&gt; e.setDeptName(hashMap.get(e.getDeptId())));6 q* @. h% c1 Q1 F; e. ^+ P
}
) k0 ]+ X" s" R3 q- n</code></pre>0 Y- i# k0 K7 U
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>- y% I$ M& P8 _- }
<h5 id="2理论分析-2">2、理论分析</h5>
4 ?% Y6 e7 o/ \: h3 V9 x1 _<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>0 d% J. C! b# d
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>& C0 q0 A1 S+ U/ `7 q
<h3 id="三一对多查询">三、一对多查询</h3>
7 X1 E+ k, b- d4 W1 M<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>* R: n6 i9 X3 A! p
<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
- F# M9 V2 f' A2 `' E' v<h5 id="1示例代码-3">1、示例代码</h5>% R2 ^6 z' j; @. C2 Z
<pre><code class="language-java">/**' Q4 a7 n5 o8 y# v% s( p/ d: w
* 查询单个部门(其中一个部门有多个用户)
% c! O+ H. v0 |3 \1 `3 G  ~ */& A! G6 m1 C5 `3 }1 B( m
public DeptVo getOneDept(Integer deptId) {
, ^0 g0 V. e1 W/ a0 b* p    // 查询部门基础信息$ g: q" n9 }% g/ H' {
    LambdaQueryWrapper&lt;Dept&gt; wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);/ p+ Z; Z( A9 z' j/ y6 U
    DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
4 N. c3 f3 o7 q    Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);
! K6 [) z6 ^& ?    return deptVo;
9 n7 e7 V4 s% S+ [- A0 C: c" o}
, Y6 `6 n5 u+ j( G- i; e) U- D</code></pre>' t( l  k0 {7 G  W! Q* H4 \* x) i
<p>补充附加信息</p>
: ?' {. a- ~5 Q) T; [* [<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {- e3 ?0 ~5 ?8 b  ~
    // 根据部门deptId查询学生列表
* F* ~" y/ }2 o  P. B    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());
, u) q  w7 U& y! f7 Z    List&lt;User&gt; users = userMapper.selectList(wrapper);& s# P) d, O" Q6 E
    deptVo.setUsers(users);
, k0 n) a1 n, L+ I9 Q0 {; b}: m" N7 Q5 N$ M/ i$ h9 P9 P
</code></pre>
* w9 R4 p* _9 [3 O<h5 id="2理论分析-3">2、理论分析</h5>5 ~1 y  [! ]+ `9 h) W+ e* Y
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>* T! d0 y5 \- H4 E2 o+ P
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>. k6 P8 J& q  b; q& j/ C; ~. T
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>1 m, X) f+ A: P. p. W* ^
<h5 id="1示例代码-4">1、示例代码</h5># ~6 G4 R4 K( n9 J: @
<pre><code class="language-java">/**. P5 v0 o- m% c  m: T( j
* 查询多个部门(其中一个部门有多个用户)5 b5 g& l7 `( ~. h9 l
*/
& ^/ @9 Y* N8 }public List&lt;DeptVo&gt; getDeptByList() {* v$ U, J; u9 Y, V
    // 按条件查询部门信息
, }& ?9 F* a4 {$ P! O    List&lt;Dept&gt; deptList = deptMapper.selectList(Wrappers.emptyWrapper());$ k9 r% Q3 L- Y
    List&lt;DeptVo&gt; deptVos = deptList.stream().map(DeptVo::new).collect(toList());
6 b# T8 E: T: K, J  v  f* Q2 U1 {    if (deptVos.size() &gt; 0) {4 S, X' c" L6 @6 K/ W
        addUserInfo(deptVos);
" [9 ~2 F; h- F4 ^5 k, r    }8 W# t  Q& G( q5 O9 L
    return deptVos;
' |" i, O6 q8 E. Y, B}, b# r: K0 r+ A  l5 N4 X
</code></pre>
1 ?5 `6 i( O( N- e1 Q<p>补充附加信息</p>
) W. K( H6 h, z<pre><code class="language-java">private void addUserInfo(List&lt;DeptVo&gt; deptVos) {
& u. ~6 D9 z% {! r" b% ?. |6 N% c    // 准备deptId方便批量查询用户信息
# {* q8 l: k) n/ G    Set&lt;Integer&gt; deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());, j$ H# [* ^( x, J
    // 用批量deptId查询用户信息
$ o, z% s+ W( n. p5 a    List&lt;User&gt; users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
- v0 L; k2 a0 `( H    // 重点:将用户按照deptId分组
" W" A( v' }7 F2 M    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));# c; D* E$ H- Q: e5 ?
    // 合并结果,构造Vo,添加集合列表* g1 p# F  u9 ?2 [
    deptVos.forEach(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));' y# \+ q+ L* w$ Z9 v
}& }& }* Q. j  }* y* T0 b/ y
</code></pre>
: U; ^' p6 t0 b0 ]; M+ f<h5 id="2理论分析-4">2、理论分析</h5>
5 p# E7 i+ k% V/ p<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>/ `: A9 {' {0 w2 f3 F. `) k
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>9 r* k% ^) v- Q. T/ A6 J
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>  x% @0 ^5 ?+ a+ {' P4 D" G% D& C
<h5 id="1示例代码-5">1、示例代码</h5>
; ^9 ?" q, A, \- t+ e) C: ?<pre><code class="language-java">/**% {2 F! [7 y$ o8 `% `, z
* 分页查询部门信息(其中一个部门有多个用户)# n8 K& `7 ~" v( r
*/9 v4 o; ^- w4 V) ^' n7 P. p' ~  m
public IPage&lt;DeptVo&gt; getDeptByPage(Page&lt;Dept&gt; page) {
; t# M: ^8 g0 v% E    // 按条件查询部门信息0 ?% o1 C6 ^* B4 s! p. k; A" D% k
    IPage&lt;Dept&gt; xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
! J! s3 c$ t, g7 O    IPage&lt;DeptVo&gt; deptVoPage = xDeptPage.convert(DeptVo::new);
; @9 a# H2 {" g, X    if (deptVoPage.getRecords().size() &gt; 0) {
1 Q, ^0 h; ~3 e  J        addUserInfo(deptVoPage);
+ e# U2 L, D% |$ k9 ~    }
7 P' c+ V7 ^& h" @    return deptVoPage;+ _" S' P) w8 I1 U" s. b
}
. Z( |' U/ Z! B( n! N- J</code></pre>, ?3 |, q/ W/ j- E, U: Q( ^
<p>查询补充信息</p>
7 d. C3 l$ l/ A/ H9 {: u+ w<pre><code class="language-java">private void addUserInfo(IPage&lt;DeptVo&gt; deptVoPage) {
5 L/ x; M. t# {8 p+ X    // 准备deptId方便批量查询用户信息! s- N  g/ p' f  ^7 D
    Set&lt;Integer&gt; deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());" }/ Q" |3 L5 u( ~8 p5 d$ h
    LambdaQueryWrapper&lt;User&gt; wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);
  @2 @5 T2 Z7 N6 J! V' z# m: i    // 用批量deptId查询用户信息9 F3 i  h( p* Z6 [2 L* Q' A( E  K1 ~
    List&lt;User&gt; users = userMapper.selectList(wrapper);, l1 a/ O9 }% A0 \  I" \* F
    // 重点:将用户按照deptId分组
9 m0 ~. e8 S8 U    Map&lt;Integer, List&lt;User&gt;&gt; hashMap = users.stream().collect(groupingBy(User::getDeptId));
  |+ a9 s% _; l* R0 ?0 O    // 合并结果,构造Vo,添加集合列表
( ]! t9 p7 H* n$ b& N7 e6 d    deptVoPage.convert(e -&gt; e.setUsers(hashMap.get(e.getDeptId())));
3 W# N" e& m! c" ~" X}
, T% m4 a1 q; ]' u( D( j6 t! K</code></pre>6 j( ?$ \! f( w
<h5 id="2理论分析-5">2、理论分析</h5>
7 E/ s- X! |/ i<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>
3 M1 x: U" f5 N+ P5 F3 T<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
6 t- Z! d; o5 k1 s% n0 R& z<h3 id="四多对多查询">四、多对多查询</h3>
$ p0 s6 n9 S8 T# X% M* Y5 ]<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>
; ]/ B- [, G, Q7 T+ D' @6 G<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p>
* r7 x% k) B" E. X" V<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
% T2 |  B: n5 Q, |+ B& b" R<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >. m! r6 F2 w) [( l& T
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>
8 o: q8 S: C: B: G" X8 E<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>& i9 i) o; D, v, V- I# u- `, m
<h5 id="1示例代码-6">1、示例代码</h5>% u/ I2 V) r. m) m9 n
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
( h9 m7 T4 }. j2 s5 k. k    // 通过主键查询学生信息
$ M+ u8 x7 J* Z3 E    StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);
6 d6 L1 a; O% _8 |    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);8 Q4 h# n% k; Z; }# Z4 a% k
    // 查询匹配关系
# a1 ^8 |% Z5 T" L    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);* a$ Q+ N+ ~& D( o
    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
) Y: D5 q1 F! P4 a6 n2 z    if (studentVo != null &amp;&amp; subIds.size() &gt; 0) {
, P$ v1 o4 y  P        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));4 R5 q1 h3 H$ i8 m
        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);' o) X3 x/ {3 t9 {5 ]
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);) `2 m" Z2 m. ^" ]6 u& P) G0 P
        subBoList.forEach(e -&gt; e.setScore(table.get(stuId, e.getId())));: l% d* C4 I8 D' L/ D. V
        studentVo.setSubList(subBoList);
3 A. O$ Z* |( Z, f$ J2 Y+ Y: N    }5 A" F# g: w1 I' k  i
    return studentVo;' ^8 G1 }$ J. x9 \5 D
}) ]' I" v# |3 `" w" y, d
</code></pre>
- L; n/ X  }4 o% s1 v9 y( j<h5 id="2理论分析-6">2、理论分析</h5>
# }8 k  w7 x' Q<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
7 q% ~, q6 k. g1 A  [2 r9 d<h4 id="二查询多条记录-2">(二)查询多条记录</h4>! g% w$ t% S9 s5 @' R
<h5 id="1示例代码-7">1、示例代码</h5>
( e0 C9 z9 M0 {<pre><code class="language-java">public List&lt;StudentVo&gt; getStudentList() {
3 E8 Q9 a1 g* `. A6 x5 p    // 通过主键查询学生信息2 `3 u/ S5 [5 Z* b
    List&lt;StudentVo&gt; studentVoList = ConvertUtils.convertList(list(), StudentVo::new);* ~. m0 B3 U) v1 U, R3 e" f$ A
    // 批量查询学生ID: f! ]- A5 L: z# M
    Set&lt;Integer&gt; stuIds = studentVoList.stream().map(Student::getId).collect(toSet());
& L7 l( v& V" ^8 h/ ~    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
2 G% v2 l, |$ G" H$ g% c% A2 _8 a8 b( o    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
& `: g8 i2 n$ g8 \$ |0 `    // 批量查询课程ID
" n0 x4 Z& T8 `! I. P$ O3 n! g    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
+ N8 v" o: J+ c+ L, s7 D- Z( I    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {9 J2 Y- }2 i* a- F
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);
$ I  c% |$ [6 a; ^. i* c        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));8 ^9 E) ~1 C- [% X5 ?0 H
        List&lt;SubjectBo&gt; subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
' H& B5 d/ o8 z7 x) g* Y# q6 E        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
2 |1 r- s( Q/ K        for (StudentVo studentVo : studentVoList) {
# z- e3 ^( m; n5 q: X3 t            // 获取课程列表
) s! y. b1 l) R" X            List&lt;SubjectBo&gt; list = ListUtils.select(subjectBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));( J* e. Z: q7 |- O) k' P! G, k
            // 填充分数* O5 d1 g; T" o7 h! ~9 Y+ `
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));6 S0 |* |) s/ h9 C
            studentVo.setSubList(list);: T& A1 H. _/ s7 R
        }
' r; k* K3 C) b# J    }$ z$ Q! l- K. h3 s/ K" ]
    return studentVoList;
7 a6 ^9 w- ^) {& X. x}
% j  c7 ~6 C" o/ C' m</code></pre>: x2 g/ d) k. ~/ x% }$ u
<h5 id="2理论分析-7">2、理论分析</h5>4 W; I# p( L. X8 ]8 z0 c, Z
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
! n- j7 w7 W7 y<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>5 _5 n* [! r/ {) L& ~
<h5 id="1示例代码-8">1、示例代码</h5>
4 e1 ^" e& o  W; T+ d<pre><code class="language-java">public IPage&lt;StudentVo&gt; getStudentPage(IPage&lt;Student&gt; page) {
5 H9 [" U& s9 Y8 s    // 通过主键查询学生信息' \7 V: N7 V, `: N
    IPage&lt;StudentVo&gt; studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);
3 Z# K/ J8 {/ a+ v$ t5 N+ W2 H    // 批量查询学生ID
! b8 f& v4 Q  b* p9 g5 E    Set&lt;Integer&gt; stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
2 t: |- V+ l  N    LambdaQueryWrapper&lt;StuSubRelation&gt; wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
; t: Z/ a) C$ a$ }9 o6 `    // 通过学生ID查询课程分数+ R# v$ G- e" \8 r
    List&lt;StuSubRelation&gt; stuSubRelations = stuSubRelationMapper.selectList(wrapper);
2 O6 s7 v2 |) R) x- z  N, E* J% Y    // 批量查询课程ID
, i4 N5 }8 N; P- j3 @    Set&lt;Integer&gt; subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());* Z- O" T. I8 R/ G* Z, K: X) g
    if (stuIds.size() &gt; 0 &amp;&amp; subIds.size() &gt; 0) {. Q) I6 b, U6 z8 f% F, h1 r
        HashBasedTable&lt;Integer, Integer, Integer&gt; table = getHashBasedTable(stuSubRelations);+ Z. X" _$ y9 }1 X* B. j
        // 学生ID查询课程ID组
( ?; h4 }0 F: L7 d$ D5 G% V        Map&lt;Integer, List&lt;Integer&gt;&gt; map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
' p) B' o5 i8 i& W( v2 k
2 i% p* u' U  u3 T9 L8 E        List&lt;Subject&gt; subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
- Q5 W$ g1 F( g0 _4 V7 K        List&lt;SubjectBo&gt; subBoList = ConvertUtils.convertList(subList, SubjectBo::new);. U! V  ^9 a( A, _" A0 X
        for (StudentVo studentVo : studentVoPage.getRecords()) {
8 p! C* M3 ]2 q/ {! v, w: X            List&lt;SubjectBo&gt; list = ListUtils.select(subBoList, e -&gt; emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));9 P, n1 E% Y/ @
            list.forEach(e -&gt; e.setScore(table.get(studentVo.getId(), e.getId())));3 Q; p) @9 S9 P; [
            studentVo.setSubList(list);: p5 t% q5 n/ p' \3 W
        }2 K0 b, V) V* \/ {
    }
) B/ a; O: e( k4 R8 G    return studentVoPage;
2 o3 Y# G% J; w: g}
7 t! ?- ~; b4 p) }( E2 G: @* h) A</code></pre>
9 U% `: f1 w5 J<h5 id="2理论分析-8">2、理论分析</h5>- E2 |& n+ T4 L6 ]( F) S
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>; S4 ?9 _% ~. l& C
<h3 id="五总结与拓展">五、总结与拓展</h3>
; y7 T+ N% F" B5 t<h4 id="一总结">(一)总结</h4>* p: p6 v$ `3 l8 {# U" I" u, A
<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
$ P7 }3 v5 w  s6 g<ul>
  {3 d3 ^+ X: @/ y' H1 Y<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
1 z) I' v. E% s<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
, r6 r/ y: P& _" U<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
' k/ d( m1 z) E* W6 |8 g- }</ul>
* F9 \) i7 W; s3 j+ B8 |<h4 id="二拓展">(二)拓展</h4>
* j) u) x7 E/ ]  L% E' a# G<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
, u6 Z* _' v5 P. F- t0 R$ Y<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>" }" a! L" X/ g5 Q
<ul>
0 ?/ D- t9 m& `5 q/ v( ~' Q<li>当数据量较大时,仍然具有稳定的查询效率</li>7 Z$ p0 y- r3 J% e8 q, S
</ul>
$ x8 |8 f1 p# m! @0 h<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>
4 h: J( b& y! ^/ W: h, @" S; {: @<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>$ z, I: ~5 z' R; }
<ul>) n0 M9 _8 l7 F/ z0 K. P
<li>与二级缓存配合使用进一步提高查询效率</li>0 n6 y5 w; K9 z
</ul>& }7 ~7 N" l5 h) y+ M$ p
<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>
2 O- v$ ]) T. l' A( Y" t. i5 H% C; A4 g& @<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>
. L1 R3 Q( t2 [$ E& A* K7 c+ f$ t! s2 X% O
回复

使用道具 举报

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

本版积分规则

手机版|飞雪团队

GMT+8, 2025-12-14 04:12 , Processed in 0.065795 second(s), 22 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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