更新時(shí)間:2022-10-08 09:53:23 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽1578次
Mybatis 作為一個(gè)被廣泛使用的 ORM 開(kāi)源框架,具有很大的靈活性,在四個(gè)組件(Excutor、StatementHandler、ParameterHandler、ResultHandler)處理簡(jiǎn)單易用的插件擴(kuò)展機(jī)制,Mybatis 對(duì) Long 層的操作是借助四個(gè)核心對(duì)象。Mybatis支持用插件攔截四個(gè)核心對(duì)象,是Mybatis插入一個(gè)就是攔截器,增強(qiáng)核心對(duì)象的功能,增強(qiáng)本質(zhì)上是借助底層動(dòng)態(tài)代理來(lái)實(shí)現(xiàn)的, 也就是說(shuō),Mybatis 中的四個(gè)對(duì)象都是代理對(duì)象
Mybatis 允許的攔截方式如下:
actuator Executor(update、query、commit、rollback Other methods );
Parameter processor ParameterHandler(getParameterObject、setParameters Method );
Result set processor ResultSetHandler(handleResultSets、handleOutputParameters Other methods );
SQL Syntax builder StatementHandler(prepare、parameterize、batch、update、query Other methods );
當(dāng)四個(gè)對(duì)象被創(chuàng)建時(shí),
1. Each created object is not returned directly , It is interceptorChain.pluginAll(parameterHandler);
2. All that you get interceptor( Interceptor ){ The interface that the plug-in needs to implement }; call interceptor.plugin(target);
return target Packed object ;
3. Plug-in mechanism , We can use the plug-in as the target object ;AOP( Face to face ) Our plug-in can create proxy objects for four objects
, The proxy object can intercept each execution of the four objects ;
簡(jiǎn)單攔截 Executor 的具體實(shí)現(xiàn)類(lèi)獲取代碼:
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? this.defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Object executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (this.cacheEnabled) {
// Second level cache Executor
executor = new CachingExecutor((Executor)executor);
}
// Every Executor example , Will be passed by interceptorChain To deal with
Executor executor = (Executor)this.interceptorChain.pluginAll(executor);
return executor;
}
In the actual development process , We use it a lot Mybaits Plugins are paging plugins ,
Through the paging plug-in, we can write without count Statement and limit Of In this case, you can get paging
Later data , It brings us great convenience in development . Except paging , Plug in usage scenarios mainly include
Update the common fields of the database , Sub database and sub table , Encryption and decryption, etc .
1.Mybatis插件接口-interceptor
intercept 方法,
插件插件方法的核心方法,生成
setProperties 方法的目標(biāo) Proxy 對(duì)象,傳遞插件所需的參數(shù)
2.自定義插件
設(shè)計(jì)并實(shí)現(xiàn)一個(gè)自定義插件:
package com.lg.plugin;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import java.sql.Connection;
import java.util.Properties;
@Intercepts({
// Notice the curly braces , In other words, there can be more @Signature Intercept multiple places , All use this interceptor
@Signature(type = StatementHandler.class, // Which class to intercept
method = "prepare", // Which method to intercept
args = {
Connection.class,Integer.class}) // To avoid intercepting overloaded methods , Pass in interception parameters , The input parameter must be consistent with the input parameter type of the interception method
})
public class MyPlugin implements Interceptor {
// As can be seen from the above principles , When the target method of the target object is executed , Every time I do intercept Method
public Object intercept(Invocation invocation) throws Throwable {
System.out.println(" Enhance the method ...");
return invocation.proceed();
}
// The target class object that will be intercepted , As the reference , Incoming interceptors , The interceptor acts as a proxy , Generate proxy objects
/** * Packaging target object , Create a proxy object for the target object * @param target For intercepted objects * @return Proxy object */
public Object plugin(Object target) {
return Plugin.wrap(target,this);
}
// Get the properties of the configuration file
// When the plug-in is initialized, call , It's only called once , The properties of plug-in configuration come in from here
public void setProperties(Properties properties) {
System.out.println(" The parameter received is ==>" + properties);
}
}
開(kāi)發(fā)步驟:
導(dǎo)入通用 PageHelper 坐標(biāo)
在核心配置文件PageHelper插件中配置mybatis
測(cè)試尋呼數(shù)據(jù)采集
1.導(dǎo)入通用PageHelper坐標(biāo)
<!-- Paging assistant -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.7.5</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9.1</version>
</dependency>
2.核心配置文件PageHelper插件中的mabatis配置
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
3.測(cè)試分頁(yè)代碼實(shí)現(xiàn)
// Test paging
@Test
public void testPage(){
PageHelper.startPage(1,3);
StuDao mapper = sqlSession.getMapper(StuDao.class);
List<Stu> stus = mapper.selectList();
for (Stu stu:
stus) {
System.out.println(stu.toString());
}
PageInfo<Stu> stuPageInfo = new PageInfo(stus);
System.out.println(" Total page number ==>" + stuPageInfo.getPages());
System.out.println(" Total number of articles ==>" + stuPageInfo.getTotal());
System.out.println(" The current page ==>" + stuPageInfo.getPageNum());
}
結(jié)果 :
什么是通用映射器?
Universal Mapper 這個(gè)是為了解決單表的增刪改查問(wèn)題,基于Mybatis的插件機(jī)制,開(kāi)發(fā)者不用寫(xiě)sql,也不需要DAO里面的Add方法,直接寫(xiě)實(shí)體類(lèi),可以支持相應(yīng)的增刪改查方法
如何使用 ?
1.導(dǎo)入通用映射器依賴(lài)
<!-- Universal Mapper-->
<!-- https://mvnrepository.com/artifact/tk.mybatis/mapper -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.4.5</version>
</dependency>
2.在核心配置文件mapper插件中的mabatis配置
<plugin interceptor="tk.mybatis.mapper.mapperhelper.MapperInterceptor">
<!-- Specifies the current generic mapper Which interface is used -->
<property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
</plugin>
3.設(shè)置實(shí)體類(lèi)的主鍵,設(shè)置表名
package com.lg.pojo;
import javax.persistence.*;
/** * Student information sheet */
@Table(name = "Stu") // Map a table
public class Stu {
@Override
public String toString() {
return "Stu{" +
"sid=" + sid +
", sname='" + sname + '\'' +
", gender='" + gender + '\'' +
", phone='" + phone + '\'' +
", hobby='" + hobby + '\'' +
", info='" + info + '\'' +
'}';
}
@Id // Corresponding to the annotation id
@GeneratedValue(strategy = GenerationType.IDENTITY) // mysql yes IDENTITY Self increasing ,Oracle yes SEQUENCE Sequence
private int sid;
@Column(name = "sname") // Consistent names , No need to write
private String sname;
private String gender;
private String phone;
private String hobby;
private String info;
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
4.定義是通用的Mapper
// Just inherited Mapper Interface can
public interface StuMapper_Plugin extends Mapper<Stu> {
}
測(cè)試班:
// Test common Mapper plug-in unit
@Test
public void testMapper(){
StuMapper_Plugin mapper = sqlSession.getMapper(StuMapper_Plugin.class);
Stu stu = new Stu();
stu.setSid(313);
Stu stu1 = mapper.selectOne(stu);
System.out.println(stu1.toString());
// 2. Example Method
Example example = new Example(Stu.class);
example.createCriteria().andEqualTo("sid",313);
mapper.selectByExample(example);
}
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問(wèn)老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743