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