攔截器需要實現 interceptor接口
public interface Interceptor { //3 對目標對象攔截進行處理的內容 Object intercept(Invocation invocation) throws Throwable; //2 確定是否執行攔截並返回一個攔截對象 攔截器連InterceptorChain 會根據返回的值執行
//調用Proxy.newProxyInstance(type.getClassLoader(),interfaces,new Plugin(target, interceptor, signatureMap));
// 創建代理對象
Object plugin(Object target);
// 1 setProperties方法是用於在Mybatis配置文件中指定一些屬性的 void setProperties(Properties properties); }
攔截器執行順序:
1 先執行setProperties
<plugin interceptor="com.tiantian.mybatis.interceptor.MyInterceptor">
<property name="prop1" value="prop1"/>
<property name="prop2" value="prop2"/>
</plugin>
根據property 屬性設置setProperties
2 新建可攔截對象的時候會調用plugin方法來決定是返回目標對象本身還是代理對象。
3當StatementHandler 代理對象在執行方法prepare參數類型為java.sql.Connection.class 的時候就會觸發當前的攔截器的intercept方法進行攔截
最后執行intercept
攔截器注解:
@Intercepts({@org.apache.ibatis.plugin.Signature(type=StatementHandler.class, method="prepare", args={java.sql.Connection.class})})
當mybatis是 的時候返回代理對象,其他返回目標對象
type:是要攔截的對象 ,method 攔截什么方法,args 方法的參數是什么
mybatis 能攔截以下四個對象: Executor, StatementHandler,ParameterHandler,ResultHandler對象
Executor:
(1、根據傳遞的參數,完成SQL語句的動態解析,生成BoundSql對象,供StatementHandler使用;
(2、為查詢創建緩存,以提高性能;
(3、創建JDBC的Statement連接對象,傳遞給StatementHandler對象,返回List查詢結果。
StatementHandler :就是和數據庫對話
(1、當我們需要改變sql的時候,顯然我們要在預編譯SQL(prepare方法前加入修改的邏輯),功能:分頁,機構過濾等需要修改原始sql
(2、當我們需要修改參數的時候我們可以在調用parameterize方法前修改邏輯。或者使用ParameterHandler來改造設置參數。
ParameterHandler
(1、ParameterHandler是用來設置參數規則的,setParameters()是設置參數的,相當於對一條sql所有的參數都執行ps.setXXX(value);
ResultHandler:將sql執行返回的結果封裝轉換為java實體類