Mybatis插件介紹
為了提高M(jìn)ybatis的可擴(kuò)展能力,Mybatis引入的插件機(jī)制,允許開發(fā)人員通過責(zé)任鏈編程的方式對目標(biāo)類進(jìn)行代理。通過閱讀源碼可知,Mybatis允許開發(fā)人員對Mybatis中的Executor、ParameterHandler、StatementHandler、ResultHandler進(jìn)行代理。有一點(diǎn)AOP的味道。
Interceptor(攔截器)
Mybatis通過Interceptor來定義一個(gè)攔截器,Interceptor在Mybatis中是一個(gè)很重要的接口,通過這個(gè)接口我們可以對前面提高的四個(gè)類進(jìn)行攔截,從而可以在這些類方法執(zhí)行前后加入我們寫的攔截邏輯。下面我們來看看Interceptor是如何定義的:
public interface Interceptor {
Object intercept(Invocation invocation) throws Throwable;
Object plugin(Object target);
void setProperties(Properties properties);
}
這個(gè)類定義的三個(gè)方法:
- intercept:這個(gè)方法用于實(shí)現(xiàn)主要的攔截邏輯。方法的入?yún)⑹且粋€(gè)
Invocation類的實(shí)例,Invocation代表目標(biāo)類的一次調(diào)用,通過它我們可以獲得被攔截的目標(biāo)類,被攔截的方法以及方法的入?yún)?。intercept方法放回一個(gè)Object實(shí)例。 - plugin:這個(gè)方法用來判定是否要對目標(biāo)類進(jìn)行攔截,也就是說是否返回被攔截類本身還是返回被攔截類的一個(gè)代理。這個(gè)方法可以與Mybatis中的
Plugin類配合使用,有關(guān)Plugin類的用法后面會(huì)講到。 - setProperties:這個(gè)方法主要用來獲取在Mybatis中配置的系統(tǒng)屬性。
Plugin
我們在描述Interceptor中的plugin方法時(shí),我們提到過該類,這個(gè)類主要的作用是通過在目標(biāo)類上使用注解的方式來決定是否要對目標(biāo)類進(jìn)行代理。'Talk is cheep, show me the code.',下面我們就來看看Plugin的實(shí)現(xiàn):
通過Plugin類的簽名我們可以看到這個(gè)類實(shí)現(xiàn)了InvocationHandler接口,并且定義了target、interceptor、signatureMap三個(gè)實(shí)例變量。

wrap方法傳入一個(gè)目標(biāo)對象和一個(gè)攔截器對象,首先通過getAllInterfaces這個(gè)方法獲取目標(biāo)類所時(shí)間的接口,然后根據(jù)接口的數(shù)量來決定是否要目標(biāo)的一個(gè)代理。

Plugin中invoke方法首先獲取目標(biāo)類被攔截的方法,如果是被攔截的方法則調(diào)用攔截器的intercept方法,所以要使攔截器鏈繼續(xù)沿著鏈路調(diào)用下去,則在攔截器中需要調(diào)用Invocation.proceed的方法。

getSignatureMap主要用來獲取攔截器上的
Intercepts注解,根據(jù)注解的值來獲取攔截器想攔截的目標(biāo)對象。我們可以看一下Intercepts的定義:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Intercepts { Signature[] value();}
Signature的定義:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Signature {
Class<?> type(); String method(); Class<?>[] args();
}

說了這么多有關(guān)Mybatis插件的實(shí)現(xiàn),那我們應(yīng)該如何使用Mybatis的插件呢?
Interceptor的使用
下面我們實(shí)現(xiàn)一個(gè)簡單攔截器HelloWorldIntercetor:
/** * 對StatementHandler的prepare方法進(jìn)行攔截 */
@Intercepts(
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}))
public class HelloWorldInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
System.out.println("I'm HelloWorld Interceptor");
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
System.out.println(properties.get("prop1"));
}
}
然后在Mybatis的的配置文件中配置:
<properties>
<property name="prop1" value="prop1"/>
</properties>
<plugins>
<plugin interceptor="mybatis.interceptor.HelloWorldInterceptor" /
</plugins>
如與Spring集成的話則在配置SqlSessionFactoryBean時(shí)進(jìn)行配置如下:
<property name="plugins">
<array>
<bean class="mybatis.interceptor.HelloWorldInterceptor" />
</array>
</property>
<property name="configurationProperties">
<props>
<prop key="prop1">prop1</prop>
</props>
</property>
通過前面的講解我們大致了解了Mybatis插件的配置使用和原理。下面我們就來看看如何寫一個(gè)Mybatis的分頁插件呢?
Mybatis分頁插件
為什么要寫一個(gè)分頁插件呢?我們在寫分頁查詢的時(shí)候系要寫列表查詢又要寫總量查詢,而且這兩個(gè)查詢的SQL很相似,在寫這一類查詢的時(shí)候有點(diǎn)浪費(fèi)時(shí)間。
在我們了解了Mybatis的插件機(jī)制后,寫一個(gè)分頁插件就比較容易了,主要的思路是根據(jù)查詢?nèi)雲(yún)Σ樵僑QL進(jìn)行改寫。下面我就直接上分頁插件的源代碼了。
/** * 分頁攔截器 */
// 對StatementHandler的prepare方法進(jìn)行攔截。
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class PageInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
RoutingStatementHandler target = (RoutingStatementHandler)invocation.getTarget();
BoundSql boundSql = target.getBoundSql();
Object paramObject = boundSql.getParameterObject();
if (hasPagerParam(paramObject)) {
Pager pager = getPagerParam(paramObject);
String sql = boundSql.getSql();
pager.setTotal(getTotal(invocation, target));
String pageSql = getPageSql(sql, pager);
FieldUtils.setFieldValue(boundSql, "sql", pageSql);
}
return invocation.proceed();
}
private String getPageSql(String sql, Pager pager) {
return String.format("%s LIMIT %d, %d", sql, pager.getIndex(), pager.getSize() );
}
private boolean hasPagerParam(Object paramObject) {
if (paramObject instanceof Pager) {
return true;
}
if (paramObject instanceof Map) {
Map<Object, Object> map = (Map<Object, Object>)paramObject;
for (Object value : map.values()) {
if (value instanceof Pager) {
return true;
}
}
}
return false;
}
private Pager getPagerParam(Object paramObject) {
if (paramObject instanceof Pager) {
return (Pager)paramObject;
}
if (paramObject instanceof Map) {
Map<Object, Object> map = (Map<Object, Object>)paramObject;
for (Object value : map.values()) {
if (value instanceof Pager) {
return (Pager)value;
}
}
}
return null;
}
private int getTotal(Invocation invocation, RoutingStatementHandler statementHandler) throws SQLException {
BoundSql boundSql = statementHandler.getBoundSql();
String sql = boundSql.getSql();
String countSql = getCountSql(sql);
FieldUtils.setFieldValue(boundSql, "sql", countSql);
Connection connection = (Connection)invocation.getArgs()[0];
Integer timeout = (Integer)invocation.getArgs()[1];
Statement statement = statementHandler.prepare(connection, timeout);
if (statement instanceof PreparedStatement) {
PreparedStatement ps = (PreparedStatement)statement;
ps.execute();
ResultSet rs = ps.getResultSet();
while (rs.next()) {
return rs.getInt(1);
}
} else {
statement.execute(countSql);
ResultSet rs = statement.getResultSet();
while (rs.next()) {
return rs.getInt(1);
}
}
return 0;
}
private String getCountSql(String sql) {
return String.format("SELECT COUNT(1) FROM(%s) _t", sql);
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {}
}
該分頁插件的實(shí)現(xiàn)方式是根據(jù)查詢參數(shù)中是否有Pager對象來判定是否應(yīng)該進(jìn)行分頁查詢,只支持mysql dialect,使用起來有一定的局限性,當(dāng)然要擴(kuò)展支持其他的數(shù)據(jù)庫也是比較容易的事情,若我們使用的是Mysql數(shù)據(jù)庫,且對性能要求不是很高的情況下,為何不使用一下分頁插件呢?