Mybatis 插件開發

都快忘了咋開發插件了,這裏從新記錄一下。後面有時間寫個自動下劃線轉駝峯插件和分頁插件吧。現在就先寫個簡單的插件例子

 

1、首先創建類實現Interceptor,可以攔截四個類 本例攔截Executor類 攔截方法query

package com.back.plugin;

import java.util.Properties;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
/**
 * mybatis插件開發 可攔截四個接口:
 * ResultSetHandler StatementHandler ParameterHandler  Executor
 * Executor 可以攔截增刪改查方法,本示例攔截的所有查詢的方法
 * @author back
 *
 */
@Intercepts({
	@Signature(type=Executor.class, method="query", args={MappedStatement.class, Object.class, 
			RowBounds.class,ResultHandler.class})
})
public class BackExecutorInterceptor implements Interceptor{

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		Object[] args = invocation.getArgs();
		System.out.println("111");
		MappedStatement ms = (MappedStatement)args[0];
		BoundSql boundSql = ms.getBoundSql(args[1]);
		System.out.println("本次調用執行sql : " + boundSql.getSql());
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
		
	}

}

2、將plugin設置生效 在mybatis-config.xml中設置 這裏的property是沒有用的 只不過展示 可以傳參 類中的setProperties能收到

<plugins>
		<plugin interceptor="com.back.plugin.BackExecutorInterceptor" >
				<property name="prop" value="11"/>
		</plugin>
	</plugins>

3、之所以展示Executor是因爲寫例子過程中發現,Executor有兩個query方法,但是有BoundSql和CacheKey的方法攔截不生效,這裏展示了下 攔截第一個後自己獲得BoundSql來進行一些處理,我這裏只是打印了下sql

4、調用Api,發現plugin生效:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章