mybatis @Intercepts的用法

1.拦截器类

package com.testmybatis.interceptor;

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.mapping.SqlSource;
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.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;

@Intercepts({ @org.apache.ibatis.plugin.Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) })
public class SqlInterceptor implements Interceptor {
	
	private Logger log=Logger.getLogger(getClass());

	public Object intercept(Invocation invocation) throws Throwable {
		// TODO Auto-generated method stub

		log.info("Interceptor......");

		// 获取原始sql语句
		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
		Object parameter = invocation.getArgs()[1];
		BoundSql boundSql = mappedStatement.getBoundSql(parameter);
		String oldsql = boundSql.getSql();
		log.info("old:"+oldsql);

		// 改变sql语句
		BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), oldsql + " where id=1",
				boundSql.getParameterMappings(), boundSql.getParameterObject());
		MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
		invocation.getArgs()[0] = newMs;

		// 继续执行
		Object result = invocation.proceed();
		return result;
	}

	public Object plugin(Object target) {
		// TODO Auto-generated method stub
		return Plugin.wrap(target, this);
	}

	public void setProperties(Properties properties) {
		// TODO Auto-generated method stub

	}

	// 复制原始MappedStatement
	private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
		MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource,
				ms.getSqlCommandType());
		builder.resource(ms.getResource());
		builder.fetchSize(ms.getFetchSize());
		builder.statementType(ms.getStatementType());
		builder.keyGenerator(ms.getKeyGenerator());
		if (ms.getKeyProperties() != null) {
			for (String keyProperty : ms.getKeyProperties()) {
				builder.keyProperty(keyProperty);
			}
		}
		builder.timeout(ms.getTimeout());
		builder.parameterMap(ms.getParameterMap());
		builder.resultMaps(ms.getResultMaps());
		builder.cache(ms.getCache());
		builder.useCache(ms.isUseCache());
		return builder.build();
	}

	public static class BoundSqlSqlSource implements SqlSource {
		BoundSql boundSql;

		public BoundSqlSqlSource(BoundSql boundSql) {
			this.boundSql = boundSql;
		}

		public BoundSql getBoundSql(Object parameterObject) {
			return boundSql;
		}
	}

}

2.拦截器配置





	
		
	

	
		
			
			
				
				
				
				
			
		
	
	
	
		
	
	

3.测试接口及配置

package com.testmybatis.model;

import java.io.Serializable;

public class Test implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int id;
	private String name;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public String toString(){
		return "id:"+id+" name:"+name;
	}

}
package com.testmybatis.dao;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.testmybatis.model.Test;


public interface TestMapper {
	public List test();
}




	

4.测试

	try {
			String resource = "com/testmybatis/mybatis-config.xml";
			InputStream inputStream = Resources.getResourceAsStream(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			SqlSession session = sqlSessionFactory.openSession();
			try {
				TestMapper mapper=session.getMapper(TestMapper.class);
				List tests=mapper.test();
				session.commit();
				log.info(JSON.toJSONString(tests));
				
			} finally {
				session.close();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

5.结果

配置了拦截器的情况下

2018-08-07 14:14:18 DEBUG [com.testmybatis.dao.TestMapper.test] ==>  Preparing: select * from test where id=1 
2018-08-07 14:14:18 DEBUG [com.testmybatis.dao.TestMapper.test] ==> Parameters: 
2018-08-07 14:14:18 DEBUG [com.testmybatis.dao.TestMapper.test] <==      Total: 1
2018-08-07 14:14:18 INFO [com.testmybatis.testlanjie] [{"id":1,"name":"adb"}]

没配置拦截器的情况下

2018-08-07 14:15:48 DEBUG [com.testmybatis.dao.TestMapper.test] ==>  Preparing: select * from test 
2018-08-07 14:15:48 DEBUG [com.testmybatis.dao.TestMapper.test] ==> Parameters: 
2018-08-07 14:15:48 DEBUG [com.testmybatis.dao.TestMapper.test] <==      Total: 8
2018-08-07 14:15:48 INFO [com.testmybatis.testlanjie] [{"id":1,"name":"adb"},{"id":2,"name":"dafdsa"},{"id":3,"name":"dafa"},{"id":4,"name":"fffff"},{"id":16,"name":"test"},{"id":17,"name":"test"},{"id":18,"name":"test"},{"id":19,"name":"zhenshide"}]

 

你可能感兴趣的:(java,mybatis)