package com.hesj.crm.plugin;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.util.Properties;
@Intercepts({@Signature(
type= Executor.class,
method = "query",
args = {MappedStatement.class,Object.class, RowBounds.class, ResultHandler.class})})
public class ExamplePlugin implements Interceptor {
Properties properties=new Properties();
//真是業務處理方法
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
//1 sql語句構造對象 包括全局配置, 綁定的sql
MappedStatement mappedStatement= (MappedStatement) args[0];
//2 實際調用的參數 keyword
Object parameter=args[1];
//3 RowBounds: 查詢傳回行數: 開始位置, 查詢記錄數
RowBounds rowBounds= (RowBounds) args[2];
//4 結果處理器
ResultHandler resultHandler= (ResultHandler) args[3];
//5 擷取執行
Executor executor= (Executor) invocation.getTarget();
//先擷取到原來的sql
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
String sql = boundSql.getSql();
sql=sql+" limit 0,3";
boundSql=new BoundSql(mappedStatement.getConfiguration(),sql,boundSql.getParameterMappings(), parameter);
//添加一個緩存的key
CacheKey cacheKey = executor.createCacheKey(mappedStatement, parameter, rowBounds, boundSql);
//執行查詢操作
return executor.query(mappedStatement, parameter, rowBounds, resultHandler, cacheKey, boundSql);
}
//對目标方法綁定攔截器
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
this.properties=properties;
}
}
配置使用
<bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com/hesj/crm/mapper/*.xml"/>
<property name="typeAliasesPackage" value="com.hesj.crm.domain"/>
<property name="configLocation" value="classpath:mybatis-cfg.xml"/>
<!-- 注意其他配置 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<!--使用下面的方式配置參數,一行配置一個 -->
<value>
</value>
</property>
</bean>
</array>
</property>
</bean>