|
|
8 Q! A ~3 U0 g9 a& j: d! D% i
<h3 id="一序言">一、序言</h3>
4 S* ^# l' b, c5 z9 J<h4 id="一背景内容">(一)背景内容</h4>
. e' |0 P! @3 F w8 ^<p>软件应用技术架构中DAO层最常见的选型组件为MyBatis,熟悉MyBatis的朋友都清楚,曾几何时MyBatis是多么的风光,使用XML文件解决了复杂的数据库访问的难题。时至今日,曾经的屠龙者终成恶龙,以XML文件为基础的数据库访问技术变得臃肿、复杂,维护难度直线上升。</p>7 h8 ]& p; N7 j: }. a
<p>MybatisPlus对常见的数据库访问进行了封装,访问数据库大大减少了XML文件的依赖,开发者从臃肿的XML文件中获得了较大限度的解脱。</p>+ a" P3 e G( E' ^3 f# Q8 q% Y3 _( H
<p>MybatisPlus官方并没有提供多表<code>连接查询</code>的通用解决方案,然而连接查询是相当普遍的需求。解决连接查询有两种需求,一种是继续使用MyBatis提供XML文件解决方式;另一种本文提供的解决方案。</p>! N% |$ a; h) V% K6 \
<p>事实上笔者强烈推荐彻底告别通过XML访问数据库,并不断探索新式更加友好、更加自然的解决方式,现分享最新的MybatisPlus技术的研究成果。</p>
6 q' V3 y2 ?' F<img src="https://www.altitude.xin/typora/image-20211021114957682.png" >
7 ~- p" s$ t0 G7 H8 {<h4 id="二场景说明">(二)场景说明</h4>! B( L0 W2 f; b. `0 g
<p>为了说明连接查询的关系,这里以学生、课程及其关系为示例。</p>+ o1 ?8 j1 t* y
<img src="https://www.altitude.xin/typora/image-20211020194255298.png" >
( J& ^8 J0 r. D% v4 [' w<h4 id="三前期准备">(三)前期准备</h4>3 {7 H e; O( h) c$ z N1 K
<p>此部分需要读者掌握以下内容:Lambda 表达式、特别是方法引用;函数式接口;流式运算等等,否则理解起来会有些吃力。</p>
0 `7 h$ d$ J* k" ^# p& U<img src="https://www.altitude.xin/typora/image-20211021135113431.png" >& L' }( X3 @4 j7 S, k" ^+ U6 ]
<p>实体类与 Vo 的映射关系,作者创造性的引入特别构造器,合理利用继承关系,极大的方便了开发者完成实体类向 Vo 的转换。</p>! _5 g1 ^3 J) h9 [/ c+ q1 `
<p>空指针异常忽略不处理,借助[Optional]类实现,详情移步[Java8 新特性]查看。</p>& h4 q6 \& W5 q. c! g" Y/ P% P
<h3 id="二一对一查询">二、一对一查询</h3>; f" n# y0 x0 P: x
<p>一对一查询最典型的应用场景是将<code>id</code>替换成<code>name</code>,比如将<code>userId</code>替换成<code>userName</code>。</p>( c! Y& j! e' n( h; p* H$ i; V5 T9 m
<h4 id="一查询单条记录">(一)查询单条记录</h4>
$ t$ t, S% ^$ T" z) o* ?9 S<p>查询单条记录是指返回值仅有一条记录,通常是以唯一索引作为条件的返回查询结果。</p>
7 S2 R$ o/ m) \* I5 Q8 Q- N<h5 id="1示例代码">1、示例代码</h5>7 W) w! \0 U2 m- r3 M# b5 K) _" C
<pre><code class="language-java">/**7 J; \/ s) g' ~& d- J1 C
* 查询单个学生信息(一个学生对应一个部门)% W/ {! ` F9 H% X% y
*/
/ F) }& I4 M f9 s3 N$ rpublic UserVo getOneUser(Integer userId) {
+ U1 O' A% a( ]3 c, e% n0 K, r: l LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class)
3 A3 R: q+ Q; b3 w1 Q9 l0 j .eq(User::getUserId, userId);( w. n: B7 Y( c9 L( n: h
// 先查询用户信息8 K* Z( D6 D& \: A; r2 f
User user = userMapper.selectOne(wrapper);
9 a' I& |$ q9 V9 G; B5 l // 转化为Vo5 ?3 j- l- M8 c( d% x& A* \7 l5 ]. I3 i0 l
UserVo userVo = Optional.ofNullable(user).map(UserVo::new).orElse(null);
$ M2 L9 h6 e2 f: I // 从其它表查询信息再封装到Vo9 D$ Q; X3 h: N/ e
Optional.ofNullable(userVo).ifPresent(this::addDetpNameInfo);* T" M$ j, X4 m3 z' n; {
return userVo;/ O1 h7 M! x5 K9 c4 ^
}6 B2 E% U6 [$ {& e% x
</code></pre>% Q! }6 M/ p2 V; l/ F
<p>附属表信息补充</p>! h0 v1 A( u! _( }, _
<pre><code class="language-java">/**
8 p3 B- F, f7 e7 F9 g# e * 补充部门名称信息( Q1 R4 H$ @6 J0 F
*/6 z4 e2 p7 S. F. z) G
private void addDetpNameInfo(UserVo userVo) {
9 j- C& a) ?( }" N! g+ [9 s* O LambdaQueryWrapper<Dept> wrapper = Wrappers.lambdaQuery(Dept.class)
+ |8 O; R7 z; `9 u" U: k: J* {5 k .eq(Dept::getDeptId, userVo.getDeptId());
9 C7 t& n( O, D2 p Dept dept = deptMapper.selectOne(wrapper);
* t/ I6 p! w2 |' O" I) P2 s Optional.ofNullable(dept).ifPresent(e -> userVo.setDeptName(e.getDeptName()));8 {+ V* y: D o/ L$ u6 H* ~
}$ o2 J" T' e: A
</code></pre>/ z# t9 C; l+ s. w$ D) i: e8 T) b
<h5 id="2理论分析">2、理论分析</h5>
0 u* h6 R- L+ y2 ~9 {7 Q3 H$ W; t<p>查询单个实体共分为两个步骤:根据条件查询主表数据(需处理空指针异常);封装 Vo 并查询附属表数据。</p> m- R* w* q4 j- A
<p>查询结果(VO)只有一条记录,需要查询两次数据库,时间复杂度为<code>O(1)</code>。</p>7 c ^" V# c# C' ?& E0 C
<h4 id="二查询多条记录">(二)查询多条记录</h4>+ m" R4 s) P8 `9 ~- h' ^6 v+ I/ F
<p>查询多条记录是指查询结果为列表,通常是指以普通索引为条件的查询结果。</p>/ p' r- V2 |0 t3 I0 ?. i
<h5 id="1示例代码-1">1、示例代码</h5>
1 u0 w( _5 f- J- F, e! v1 x n<pre><code class="language-java">/**
7 ]- ?7 N3 |( s, Q W# f7 R * 批量查询学生信息(一个学生对应一个部门)
- l1 ~* N/ _1 Y" Q- ]) P, V1 s */# `5 ]$ i& L& F7 [/ Q( p9 T$ ?- l
public List<UserVo> getUserByList() {: A6 f9 W! i D& u# W6 K) ~+ o1 V
// 先查询用户信息(表现形式为列表): L7 K3 D4 u( e
List<User> user = userMapper.selectList(Wrappers.emptyWrapper());& y$ t4 G6 y2 `' D
List<UserVo> userVos = user.stream().map(UserVo::new).collect(toList());
, b r1 W0 B, p$ x$ x( o ~& p // 此步骤可以有多个4 \: H! I4 P/ ?% y4 n$ k) A( [( d
addDeptNameInfo(userVos);
+ q% k' ?' z5 p" Q. i$ s9 f$ u return userVos;
; v0 e& [1 I# F! U8 L}
+ s3 m% N1 {! b! M' R& X5 E</code></pre>
9 x5 A9 W* N6 V0 R" f<p>附属信息补充</p>
! |" o6 d, H$ q* e8 X/ j* \<pre><code class="language-java">private void addDeptNameInfo(List<UserVo> userVos) {
1 Q) B- R+ Y/ ~* n. m# L // 提取用户userId,方便批量查询9 f: g1 B! }' i- k
Set<Integer> deptIds = userVos.stream().map(User::getDeptId).collect(toSet());% z$ Q4 o1 L* L' N
// 根据deptId查询deptName(查询前,先做非空判断): [$ i7 v3 s1 ^' `
List<Dept> dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));
/ r3 y4 `" M9 V4 B* e- d // 构造映射关系,方便匹配deptId与deptName5 |: p& }* e6 u$ i. b3 N" U2 j
Map<Integer, String> hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));+ H0 C9 h" p* A$ F2 x" b
// 封装Vo,并添加到集合中(关键内容)& [6 F8 o5 W5 X: Y
userVos.forEach(e -> e.setDeptName(hashMap.get(e.getDeptId())));* ]# b5 x2 ]$ I9 H- t; R
}
9 m& a: d+ w0 I7 Z</code></pre># `) K0 ]- j9 @7 _" Y' u& F7 \9 Y
<h5 id="2理论分析-1">2、理论分析</h5># {# {3 C3 ?- z V2 f" r
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>
' y& @1 W! Z+ C7 M<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>% ^& `1 m+ C) B2 d Y0 o
<h4 id="三查询多条记录分页">(三)查询多条记录(分页)</h4>
- I* R4 K5 v/ `<p>分页查询实体的思路与查询列表的思路相似,额外多处一步分页泛型转换。</p>: f0 j" P5 `) S% V
<h5 id="1示例代码-2">1、示例代码</h5>
c6 s3 T1 g Q<pre><code class="language-java">/**0 |" Y+ l! [' }9 \ o" @# M
* 分页查询学生信息(一个学生对应一个部门), a7 J) m2 y8 H8 [& s. x8 n4 h5 K
*/3 W7 _/ H: k) p6 \
public IPage<UserVo> getUserByPage(Page<User> page) {/ g) Z* ]- l: F2 l( v8 L
// 先查询用户信息
' S" i& N9 ~% O' L7 l' m IPage<User> xUserPage = userMapper.selectPage(page, Wrappers.emptyWrapper());" h# u! q f3 H5 v
// 初始化Vo X9 I; d! J5 W' t+ E
IPage<UserVo> userVoPage = xUserPage.convert(UserVo::new);% v2 I) [$ V# S( `" s. W2 B
if (userVoPage.getRecords().size() > 0) {
. q) Y. i- `2 ^" |9 t: L addDeptNameInfo(userVoPage);, `% ?9 _8 J4 f' w
}
# b. H4 I3 h( Q return userVoPage;9 q4 ~" @9 {" m/ E9 H R6 t
}
. G: X+ I. \- k4 B5 o</code></pre>' V2 q$ I% W2 U/ A" M; T3 U8 g0 ?4 ^
<p>查询补充信息</p>% ?+ q; ?2 U. X: R! ]* s
<pre><code class="language-java">private void addDeptNameInfo(IPage<UserVo> userVoPage) {3 k. {, z2 `) S; q9 ~8 l
// 提取用户userId,方便批量查询
, q( d$ C y$ T; b7 P$ t* l Set<Integer> deptIds = userVoPage.getRecords().stream().map(User::getDeptId).collect(toSet());! F3 H! g( F/ t$ J; J8 U
// 根据deptId查询deptName# A: w; ?: i0 g3 `5 a& M
List<Dept> dept = deptMapper.selectList(Wrappers.lambdaQuery(Dept.class).in(Dept::getDeptId, deptIds));0 i" `) x% f. T h2 O
// 构造映射关系,方便匹配deptId与deptName) ^: S: X% u" E6 U8 c+ u9 w2 E" \, l
Map<Integer, String> hashMap = dept.stream().collect(toMap(Dept::getDeptId, Dept::getDeptName));6 w* g+ b" ?' T' y/ i0 t! _
// 将查询补充的信息添加到Vo中
" F6 V1 h2 Y+ u: S6 i- \, ? userVoPage.convert(e -> e.setDeptName(hashMap.get(e.getDeptId())));
. X6 q# U+ B: n8 w2 }0 u}
1 n/ Z! u1 ]2 Z/ `4 \3 @7 a% |</code></pre>5 F2 w1 o9 K' k+ Y7 O
<p><code>IPage</code>接口中<code>convert</code>方法,能够实现在原实例上修改。</p>% U% m) L& @. f* g# @- d, ]7 _# T
<h5 id="2理论分析-2">2、理论分析</h5># d! W% `( @7 V3 P0 C( E0 M
<p>先查询包含<code>id</code>的列表记录,从结果集中析出<code>id</code>并转化成批查询语句再访问数据库,从第二次调用结果集中解析出<code>name</code>。</p>0 {6 ]0 x% D1 V' d
<p>查询结果(VO)有多条记录,但仅调用两次数据库,时间复杂度为<code>O(1)</code>。</p>& S7 c1 ^; Q" r/ ~
<h3 id="三一对多查询">三、一对多查询</h3>( ?8 X% r/ ~8 m& [
<p>一对多查询最常见的场景是查询部门所包含的学生信息,由于一个部门对应多个学生,每个学生对应一个部门,因此称为一对多查询。</p>
: O2 }, t4 T' Z- W) r<h4 id="一查询单条记录-1">(一)查询单条记录</h4>
' |' I- B+ e9 C2 L0 u$ e/ B1 D<h5 id="1示例代码-3">1、示例代码</h5># s$ _) r0 I" J) O! ^% Z
<pre><code class="language-java">/*** a6 H, M1 G/ X* u" E7 o4 s3 u
* 查询单个部门(其中一个部门有多个用户)
! F* e2 e$ Q- n# {: u( d */
) W/ D3 k8 {- y$ \# Jpublic DeptVo getOneDept(Integer deptId) {& G( i: @& R5 J T! k% P; s: s
// 查询部门基础信息/ M5 Q5 w8 A5 @
LambdaQueryWrapper<Dept> wrapper = Wrappers.lambdaQuery(Dept.class).eq(Dept::getDeptId, deptId);
$ S% _) d- q- Y# l DeptVo deptVo = Optional.ofNullable(deptMapper.selectOne(wrapper)).map(DeptVo::new).orElse(null);
) D5 r+ p3 H. \ Optional.ofNullable(deptVo).ifPresent(this::addUserInfo);5 ? b" B* j, m
return deptVo;* N! N. o+ p: L/ Z+ E# Z
} s) B0 r; H% C4 i4 I8 \
</code></pre>& ]- n& w. s. {# K! `! L
<p>补充附加信息</p>
$ m: o# A/ k" u<pre><code class="language-java">private void addUserInfo(DeptVo deptVo) {6 v: a1 }5 B. n8 r1 z
// 根据部门deptId查询学生列表4 x! T1 E7 b8 `
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).eq(User::getDeptId, deptVo.getDeptId());. A6 w0 K) }; {' i) f0 i' Q
List<User> users = userMapper.selectList(wrapper);
4 \) j8 E9 [. |) \+ @# Z deptVo.setUsers(users);
* x& V9 J- _- F" O2 u' d# d}
4 @6 {% Z& W4 V# ]( n</code></pre>( U1 B; |; ~6 j' y9 G3 I7 c; }6 }- m
<h5 id="2理论分析-3">2、理论分析</h5>9 g" n! S+ X8 d) b+ J# {
<p>整个过程共分为两个阶段:通过部门表中主键查询指定部门信息,通过学生表中部门ID外键查询学生信息,将结果合并,形成返回值(Vo)。</p>+ |* i$ z/ i$ [* W
<p>一对多查询单条记录整个过程至多需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>0 ]6 b" Z7 ~+ F3 [0 C% y {
<h4 id="二查询多条记录-1">(二)查询多条记录</h4>
0 i6 ?1 Q* b6 Q* Q+ r( K<h5 id="1示例代码-4">1、示例代码</h5>
: E% K8 r6 X9 g7 v) c+ Y* y<pre><code class="language-java">/**
% V5 N1 G' Y1 D: w; z5 K& _/ @ * 查询多个部门(其中一个部门有多个用户)
! N) R( N+ L6 r1 a& e& b */- V+ U" v1 w( J* r, Y* ^( C
public List<DeptVo> getDeptByList() {- }3 ^7 w) e& T
// 按条件查询部门信息( I0 d! C" l1 A# `+ W2 ]
List<Dept> deptList = deptMapper.selectList(Wrappers.emptyWrapper());* E; s) O: a3 T4 ?* c, P
List<DeptVo> deptVos = deptList.stream().map(DeptVo::new).collect(toList());; y, o# [6 u8 H& E3 O2 P2 n
if (deptVos.size() > 0) {0 X" K. _4 s# |& C. W5 Q' }
addUserInfo(deptVos);
& S2 r0 T, }1 H! p' o: w0 N }5 o, L7 s/ e8 ~
return deptVos;
6 C$ Y! Z7 n' S) G. A& r}
( B, x2 m5 N9 w7 v</code></pre>: B3 }. H8 h6 H, E; \0 W8 _
<p>补充附加信息</p>
2 i. D$ O% B$ a1 t<pre><code class="language-java">private void addUserInfo(List<DeptVo> deptVos) {
j S' L8 i2 S' ?9 u // 准备deptId方便批量查询用户信息
7 S/ j% g7 S0 q3 h( P/ M: k: X& F Set<Integer> deptIds = deptVos.stream().map(Dept::getDeptId).collect(toSet());5 f( J1 m+ |7 P
// 用批量deptId查询用户信息& g! C; W# u3 h& g0 L- p. ~4 T! Q
List<User> users = userMapper.selectList(Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds));
% [! K0 }9 m& f: q( h // 重点:将用户按照deptId分组
3 k! z& J" B# n' C& J6 P Map<Integer, List<User>> hashMap = users.stream().collect(groupingBy(User::getDeptId));; I2 E5 d1 A) {. v1 U+ A% e$ k8 B
// 合并结果,构造Vo,添加集合列表% b( s- |" T7 v5 g" |$ ?2 |
deptVos.forEach(e -> e.setUsers(hashMap.get(e.getDeptId())));
) S* W" \7 G0 B2 j/ E7 p}- K$ s; p; \* C$ r
</code></pre>5 Y+ T3 s% l- X7 K7 b k
<h5 id="2理论分析-4">2、理论分析</h5>; [& l( m* o* b
<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>! u9 I, q t2 v* x0 M+ N
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>7 }- ]) k0 |! x z: p% V
<h4 id="三查询多条记录分页-1">(三)查询多条记录(分页)</h4>
2 q5 F4 q9 Y+ d+ u; Y<h5 id="1示例代码-5">1、示例代码</h5>
& f7 k5 j F) t# b! g% x0 d<pre><code class="language-java">/**
( N# l. O$ Q* u. J* }) M/ y9 y5 Z2 f * 分页查询部门信息(其中一个部门有多个用户)/ c, u! o8 e; P4 _! G3 Q2 F- |% U
*/
3 I8 L& U7 ~* c0 C1 p# F' R# @public IPage<DeptVo> getDeptByPage(Page<Dept> page) {
3 ]5 x6 @( S Q/ F0 l( K // 按条件查询部门信息
, J o( o k( D/ e5 x IPage<Dept> xDeptPage = deptMapper.selectPage(page, Wrappers.emptyWrapper());
! x1 l; l' v$ Y7 R" ]" [: ~ IPage<DeptVo> deptVoPage = xDeptPage.convert(DeptVo::new);% Y" _" g5 Z% V# B5 F$ _; J
if (deptVoPage.getRecords().size() > 0) {! F" I/ t4 _8 \$ _' v0 D
addUserInfo(deptVoPage);" L( B# w+ U3 B6 v' l7 R, g: S
}5 M, \/ i( D4 c" f
return deptVoPage;
4 l: B5 a$ m1 f, k/ u% Q" l}
, p6 T; J8 z% f5 O</code></pre>
5 j# A- o) l+ C# T0 Q& {: g6 G<p>查询补充信息</p> l2 x0 Q, B' z- ?
<pre><code class="language-java">private void addUserInfo(IPage<DeptVo> deptVoPage) {0 Y0 \4 L0 I X& q
// 准备deptId方便批量查询用户信息
4 M- J0 c, K# x: ^5 K Set<Integer> deptIds = deptVoPage.getRecords().stream().map(Dept::getDeptId).collect(toSet());" T/ E: X" d) y
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).in(User::getDeptId, deptIds);! L a% l. I, u) _; [3 I3 F& g" G
// 用批量deptId查询用户信息" s8 W2 Y" d% ]/ e, m: z4 E/ W( z
List<User> users = userMapper.selectList(wrapper);
# l" `6 @2 h/ |+ s // 重点:将用户按照deptId分组. R1 c. B/ m; r( \. ^, v
Map<Integer, List<User>> hashMap = users.stream().collect(groupingBy(User::getDeptId));2 _+ B: l1 e- E' z6 [( [! |. R
// 合并结果,构造Vo,添加集合列表
8 p4 ?; A: E \1 R+ s, [8 P! y5 Q deptVoPage.convert(e -> e.setUsers(hashMap.get(e.getDeptId())));
5 B d% b: \9 T( _}
7 ]: J, N) E4 T' j% [</code></pre>
X; g2 M& {% M3 [<h5 id="2理论分析-5">2、理论分析</h5>
) X8 d/ K7 h# K6 c3 x2 ~3 k; t<p>整个过程共分为三个阶段:通过普通索引从部门表中查询若干条记录;将部门ID转化为批查询从学生表中查询学生记录;将学生记录以部门ID为单位进行分组,合并结果,转化为Vo。</p>- ^$ L% @7 c6 R$ I& z1 L7 p
<p>一对多查询多条记录需要调用2次数据库查询,查询次数为常数,查询时间复杂度为<code>O(1)</code>。</p>
M- k1 w8 ?8 W4 S! N+ w<h3 id="四多对多查询">四、多对多查询</h3>
S. m5 U5 g( |8 Z* U- p/ D0 j" L<p>MybatisPlus 实现多对多查询是一件极富挑战性的任务,也是连接查询中最困难的部分。</p>: B+ t. B+ g1 }' }. _
<p>以空间置换时间,借助于流式运算,解决多对多查询难题。</p># ?; I2 P0 x# p! F4 f9 m, t
<p>多对多查询相对于一对多查询,增加了流式分组运算、批量 HashMap 取值等内容。</p>
3 a, L, x: L; J" M1 K1 \<img src="https://www.altitude.xin/typora/image-20211024115903848.png" >& G- f9 q; g4 M
<h4 id="一查询单条记录-2">(一)查询单条记录</h4>5 M. p# J; p& K3 J& R; E
<p>查询单条记录一般是指通过两个查询条件查询出一条匹配表中的记录。</p>$ o# G5 S6 B# x
<h5 id="1示例代码-6">1、示例代码</h5>, g; h' ]- C/ O1 L H
<pre><code class="language-java">public StudentVo getStudent(Integer stuId) {
' f6 w4 m5 ]( H: A // 通过主键查询学生信息- y% T0 c% e" s. D& k
StudentVo studentVo = ConvertUtils.convertObj(getById(stuId), StudentVo::new);; l- Y( ~& }" F3 b" @# ], r
LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).eq(StuSubRelation::getStuId, stuId);
5 _8 K1 h/ p8 [9 ]/ f) x // 查询匹配关系
+ {+ u, v" h& |# { List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);
! l3 q/ g3 k1 C. W# e2 p3 H! P p& T% s# Z Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());8 O$ G' ?0 `+ L6 e$ y9 o
if (studentVo != null && subIds.size() > 0) {% F1 v: [! C/ S2 e% F* E! {, g! U
List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
, L% f% z% C: q8 P6 J) m/ X5 a W9 K) _ List<SubjectBo> subBoList = ConvertUtils.convertList(subList, SubjectBo::new);; i& O/ V/ Y& N" M
HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);
& y1 C& D% i7 P/ F: S& {) x subBoList.forEach(e -> e.setScore(table.get(stuId, e.getId())));- k& m6 k* h: h" P
studentVo.setSubList(subBoList);6 T: m) o3 S/ h# D8 h" w" x& A1 l
}/ k/ `+ D8 B6 Q
return studentVo;6 B/ [& i" x( b% F1 f
}% L* Q- w& K$ L7 G1 u H( i& x
</code></pre>3 J( I$ |1 a8 r, g" Q! U
<h5 id="2理论分析-6">2、理论分析</h5>
/ i" G+ ~& V1 c( A, w<p>多对多单条记录查询最多访问数据库3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>; D$ d6 N! d( U' X% S& U' l- r
<h4 id="二查询多条记录-2">(二)查询多条记录</h4>
0 y1 [; S9 Q6 t9 R% X! L<h5 id="1示例代码-7">1、示例代码</h5>" z- k% a+ T. t; C4 K# ]# q# Y
<pre><code class="language-java">public List<StudentVo> getStudentList() {% r. ]6 e; H; \' M. r8 e
// 通过主键查询学生信息, h; p9 e1 z" T; l- ^ ^
List<StudentVo> studentVoList = ConvertUtils.convertList(list(), StudentVo::new);
I+ g" ~; [, I. m! ^0 O+ [4 f // 批量查询学生ID
( J% Y& W$ N4 o: U8 {! F% u Set<Integer> stuIds = studentVoList.stream().map(Student::getId).collect(toSet());& w( a4 N' e* e: d8 \4 L! J
LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
+ ]$ Y0 T O) w; ?, B2 V# q: c List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);
+ |) q8 u: ]; v1 W1 S // 批量查询课程ID1 k! A% T# K) o
Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
+ I9 Z) z7 t( L+ G; H' k8 F ^9 d if (stuIds.size() > 0 && subIds.size() > 0) {
4 A4 U- [+ W5 _ [( B$ e0 I HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);. j7 [2 P. ^( o3 f
List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
r7 I, w1 C1 C" m1 l6 d, r List<SubjectBo> subjectBoList = ConvertUtils.convertList(subList, SubjectBo::new);
5 @: j( F( \7 v( ?5 } Map<Integer, List<Integer>> map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));
" L0 H7 o4 D1 J3 { for (StudentVo studentVo : studentVoList) {
$ b" ~* O" `0 b5 l0 \( T // 获取课程列表( z' E; m; u2 [0 B' B# E
List<SubjectBo> list = ListUtils.select(subjectBoList, e -> emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));+ i" g) R- A% _/ l/ a- d! B" u& E
// 填充分数
' e6 K8 d/ S2 ?3 d: O. F list.forEach(e -> e.setScore(table.get(studentVo.getId(), e.getId())));
1 r; h# @' C* z0 K$ F) g6 Z studentVo.setSubList(list);; K8 y T s, Z" N
}
1 D' h% k; [% [- o) p }
7 f; S& h t3 u+ J2 K: D5 j return studentVoList;
( {" F1 F) Q" `7 J}
' `7 ?( ~! ]. p n6 \</code></pre>: p9 N7 P+ _( Q f7 d( Z! H. B
<h5 id="2理论分析-7">2、理论分析</h5>6 n8 _7 `* E3 k* R* U. I4 w
<p>多对多N条记录查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>5 z9 z* \8 X7 }% I! Q- N5 b/ l
<h4 id="三查询多条记录分页-2">(三)查询多条记录(分页)</h4>. h, D( U8 y2 [* T5 P4 r8 o
<h5 id="1示例代码-8">1、示例代码</h5>3 E% k! A+ N- x7 ?% M! d
<pre><code class="language-java">public IPage<StudentVo> getStudentPage(IPage<Student> page) {' H1 v) x% h$ {, V. W* R+ i
// 通过主键查询学生信息
2 z7 U( k) x0 z/ ~2 d; [7 B3 e IPage<StudentVo> studentVoPage = ConvertUtils.convertPage(page(page), StudentVo::new);' [$ P0 T8 } z: x
// 批量查询学生ID: g1 o8 D& R6 J2 w( Z
Set<Integer> stuIds = studentVoPage.getRecords().stream().map(Student::getId).collect(toSet());
1 h F) g, Z/ y LambdaQueryWrapper<StuSubRelation> wrapper = Wrappers.lambdaQuery(StuSubRelation.class).in(StuSubRelation::getStuId, stuIds);
& A0 `3 R$ q" a! c0 O) w& v // 通过学生ID查询课程分数
+ p+ }. W: }# f6 ]9 S' V4 q) j List<StuSubRelation> stuSubRelations = stuSubRelationMapper.selectList(wrapper);% T( k K$ w: o2 M" _+ Z
// 批量查询课程ID
3 M: `) ^ k3 q2 p- Z' d3 i Set<Integer> subIds = stuSubRelations.stream().map(StuSubRelation::getSubId).collect(toSet());
4 f: t* v# y8 L. M/ h if (stuIds.size() > 0 && subIds.size() > 0) {
0 v7 K+ `+ C+ l; L" Q+ k4 W HashBasedTable<Integer, Integer, Integer> table = getHashBasedTable(stuSubRelations);
5 o8 e4 t" R- t // 学生ID查询课程ID组; K2 Q5 u& w5 `( ~' i. c
Map<Integer, List<Integer>> map = stuSubRelations.stream().collect(groupingBy(StuSubRelation::getStuId, mapping(StuSubRelation::getSubId, toList())));7 s: N z. f. a6 j* `
" u) k6 ^' N- V6 Y L; i' e1 ~$ v$ M3 [
List<Subject> subList = subjectMapper.selectList(Wrappers.lambdaQuery(Subject.class).in(Subject::getId, subIds));
0 Q Q: X7 }5 t1 o$ e List<SubjectBo> subBoList = ConvertUtils.convertList(subList, SubjectBo::new);
5 s4 E# ~3 r; N; k$ H for (StudentVo studentVo : studentVoPage.getRecords()) {* O5 X J5 w2 f" O) }
List<SubjectBo> list = ListUtils.select(subBoList, e -> emptyIfNull(map.get(studentVo.getId())).contains(e.getId()));4 m* n5 D; U5 b* a
list.forEach(e -> e.setScore(table.get(studentVo.getId(), e.getId())));
9 i7 ]( r9 z" A' ? studentVo.setSubList(list);2 ?* \0 j% A) p$ @" [, B0 w* }
}, }7 f9 h' K2 v, N
}
1 ^0 g3 I6 y. n$ ` return studentVoPage; N9 `8 k, Z' u$ ]" P0 v% Q- m
}% f, h+ B( j; x, S1 i7 z
</code></pre>
6 F P- d4 W/ ~$ C3 B) F<h5 id="2理论分析-8">2、理论分析</h5>! J' W9 I- o6 n* O- u
<p>多对多N条记录分页查询由于使用了批查询,因此最多访问数据库也是3次,先查询学生信息,然后查询学生与课程匹配信息,最后查询课程分数信息,查询时间复杂度为<code>O(1)</code>。</p>
) }+ N$ M6 |! ^% I: a/ F0 x<h3 id="五总结与拓展">五、总结与拓展</h3>9 C3 _4 B4 l7 M8 a, \$ ^# }6 g
<h4 id="一总结">(一)总结</h4>
- h, c) `3 |- N) g/ w<p>通过上述分析,能够用 MybatisPlus 解决多表连接查询中的<code>一对一</code>、<code>一对多</code>、<code>多对多</code>查询。</p>
9 a, E/ \4 }, Y! ]9 o+ u<ul># Q% A* e& f/ S
<li>上述代码行文紧凑,充分利用 IDE 对 Lambda 表达式的支持,在编译期间完成对代码的检查。</li>
* _1 ]4 H& J# ^5 }' a2 E, V4 l- p9 _<li>业务逻辑清晰,可维护性、可修改性优势明显。</li>
: |* x1 n3 _# p3 E& S' J; H<li>一次查询需要访问至多两次数据库,时间复杂度为<code>o(1)</code>,主键查询或者索引查询,查询效率高。</li>
% e" Z8 }* J9 c+ ?8 Y. I, C; a1 l</ul>- R0 d5 T. B3 _5 x, [
<h4 id="二拓展">(二)拓展</h4>* J) [; U# b2 ]+ a8 ~0 L V: k
<p>MybatisPlus能很好的解决单表查询问题,同时借助在单表查询的封装能很好地解决连接查询问题。</p>
^, h5 t5 g9 j! G<p>本方案不仅解决了连接查询问题,同时具备如下内容拓展:</p>4 L$ y2 N# u" ^
<ul>
[7 b" b9 _( v/ j<li>当数据量较大时,仍然具有稳定的查询效率</li>; X* P' P: p# X+ e8 k; d4 g& g0 Y" j+ i
</ul>
1 C* j7 G/ w; K8 I) |( ]5 Z<p>当数据量达到百万级别时,传统的单表通过索引查询已经面临挑战,普通的多表连接查询性能随着数据量的递增呈现指数级下降。</p>, E! B H6 B8 h" g. C5 S
<p>本方案通过将连接查询转化为主键(索引)查询,查询性能等效于单表查询。</p>0 ~& i' g$ G+ n* F+ ~
<ul>
. B* f3 c3 j+ S4 \# v7 ?0 o# L<li>与二级缓存配合使用进一步提高查询效率</li>
; L. {3 i5 [$ ~4 m) d6 p, U2 X</ul>
( P5 |" W% `7 u' Y<p>当所有的查询均转化为以单表为基础的查询后,方能安全的引入二级缓存。二级缓存的单表增删改查操作自适应联动,解决了二级缓存的脏数据问题。</p>3 W4 @' y& W# h7 x5 ~9 M
<p><img src="https://img2022.cnblogs.com/blog/2731108/202202/2731108-20220212103110902-776916010.jpg" ></p>4 u4 w$ W' f9 m: y; n5 u1 o
7 O/ o$ R$ k. \4 F! c7 Y. k |
|