Mybatis的插件,主要用于在執行sql前后,對sql進行封裝加工,或者在sql執行后,對數據進行加工處理。常用于一些公共數據操作處理,例如:
指定需要攔截的方法,通過方法簽名來指定,方法簽名即指定哪個類的哪個方法+方法參數。這里的類不能隨便寫,只能從以下幾個類中選,也就是說,MyBatis 插件可以攔截四大對象中的任意一個。
我們來看以下mybatisplus的插件配置的簽名:
@Intercepts( { @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}), @Signature(type = StatementHandler.class, method = "getBoundSql", args = {}), @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}), @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}), })public class MybatisPlusInterceptor implements Interceptor {//...}
type指定四大類型中的任意一個,method指定攔截類型中方法,args指定方法參數。例如:
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
指定了攔截StatementHandler的prepare方法,方法有兩個參數,一個是Connection類型,另一個是Integer類型。
public interface StatementHandler { Statement prepare(Connection connection, Integer transactionTimeout) throws SQLException; //.... }
在 MyBatis 中開發插件,需要實現 Interceptor 接口。接口的定義如下:
public interface Interceptor { Object intercept(Invocation invocation) throws Throwable; Object plugin(Object target); void setProperties(Properties properties); }
創建個類實現Interceptor接口,并且在實現類上指定方法簽名即可。
最后需要在mybatis配置文件中配置插件
<plugins> <plugin interceptor="com.yjw.demo.mybatis.common.page.PageInterceptor"> </plugin> </plugins>
最后建議看一下MybatisPlusInterceptor的實現,里面還使用到了責任鏈設計模式。
本文鏈接:http://www.tebozhan.com/showinfo-26-10908-0.html一篇聊聊Mybatis插件開發
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com