import java.util.Properties;
import org.apache.ibatis.executor.Executor;
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;
//insert update delete都算作Executor的update方法 select算是query方法,详见Mybatis文档
@Intercepts( {
@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 }) })
public class PrintSqlPlugin implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
/*
*/
Object[] args = invocation.getArgs();
//MyBatis将SQL配置信息加载成为不同的MappedStatement对象并存储在内存中。
MappedStatement stmt = (MappedStatement) args[0];
//为方法传递过来的参数
Object arg = null;
/*
判断第二个参数是不是空,及是否传递过来了
IStudentMapper studentDao = session.getMapper(IStudentMapper.class);
studentDao.insert(student);
*/
if (args.length > 1) {
arg = args[1];
}
/*
*/
BoundSql boundSql = stmt.getBoundSql(arg);
String sql = boundSql.getSql();
//以下代码为格式化输出将回车和制表符换成
sql = sql.replaceAll("\n", "");
sql = sql.replaceAll("\t", "");
System.out.println(sql);
return invocation.proceed();
}
public Object plugin(Object obj) {
return Plugin.wrap(obj, this);
}
public void setProperties(Properties properties) {
}
}
//主配置文件中配置config.xml
<pre name="code" class="html"><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties"></properties>
<typeAliases>
<!--以下为实体类及其别名-->
<typeAlias alias="student" type="com.oracle.wfc.model.Student" />
</typeAliases>
<plugins>
<plugin interceptor="com.oracle.wfc.dao.PrintSqlPlugin"></plugin>
</plugins>
<!--以下数据库连接环境集,一个环境集中可以包含多个环境声明,每个环境都有自己的id,id可以任意指定,可以在环境集上用default声明哪个环境是默认的环境。
-->
<environments default="development">
<environment id="development">
<!--以下为使用JDBC管理事务,->
<transactionManager type="JDBC" />
<!--以下为配置dataSource POOLED表示使用连接池机制 ->
<dataSource type="POOLED">
<!--以下为连接数据库的属性文件-->
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
<environment>
......
</environment>
</environments>
<!--以下为声明实体映射文件的位置->
<mappers>
<mapper resource="com/oracle/wfc/dao/mapper/IStudentMapper.xml" />
</mappers>
</configuration>