mybatis|mybatis @Intercepts的用法解读
目录
- mybatis @Intercepts的用法
- 1.拦截器类
- 2.拦截器配置
- 3.测试接口及配置
- 4.测试
- 5.结果
- mybatis @Intercepts小例子
- 1.工作目录
- 2.数据库mysql
- 3.拦截器
- 4.配置文件
- 5.配置文件
- 6.测试文件
- 7.工具类
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 stubreturn 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 Listtest(); }
select * from 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); Listtests=mapper.test(); session.commit(); log.info(JSON.toJSONString(tests)); } finally {session.close(); } } catch (IOException e) {// TODO Auto-generated catch blocke.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"}]
mybatis @Intercepts小例子 这只是一个纯碎的mybatis的只针对@Intercepts应用的小列子,没有和spring做集成。
1.工作目录

文章图片
2.数据库mysql
建立一个数据库表、实体对象User、UserMapper.java、UserMapper.xml省略。
使用mybatis自动代码生成工具生成:mybatis-generator-core-1.3.2。(此处略)
3.拦截器
MyInterceptor.java
package com.tiantian.mybatis.interceptor; import java.sql.Connection; import java.util.Properties; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.executor.statement.StatementHandler; 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; @Intercepts( {@Signature(method = "query", type = Executor.class, args = {MappedStatement.class, Object.class, RowBounds.class,ResultHandler.class }),@Signature(method = "prepare", type = StatementHandler.class, args = { Connection.class }) })public class MyInterceptor implements Interceptor {@Overridepublic Object intercept(Invocation invocation) throws Throwable {Object result = invocation.proceed(); System.out.println("Invocation.proceed()"); return result; }@Overridepublic Object plugin(Object target) {// TODO Auto-generated method stubreturn Plugin.wrap(target, this); }@Overridepublic void setProperties(Properties properties) {String prop1 = properties.getProperty("prop1"); String prop2 = properties.getProperty("prop2"); System.out.println(prop1 + "------" + prop2); }}
4.配置文件
mybatis-config.xml
5.配置文件
jdbc.properties
driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/database_yxlusername=rootpassword=123456#定义初始连接数initialSize=0#定义最大连接数maxActive=20#定义最大空闲maxIdle=20#定义最小空闲minIdle=1#定义最长等待时间maxWait=60000
6.测试文件
TestMyBatis.java
package com.tiantian.mybatis.service; import org.apache.ibatis.session.SqlSession; import com.tiantian.base.MyBatisUtil; import com.tiantian.mybatis.domain.User; public class TestMyBatis {public static void main(String[] args) {SqlSession session = MyBatisUtil.getSqlSession(); /*** 映射sql的标识字符串,* com.tiantian.mybatis.mapper.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,* selectByPrimaryKey是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL*/String statement = "com.tiantian.mybatis.mapper.UserMapper.selectByPrimaryKey"; //映射sql的标识字符串//执行查询返回一个唯一user对象的sqlUser user = session.selectOne(statement, 1); System.out.println(user); }}
输出结果:
prop1------prop2
Invocation.proceed()
Invocation.proceed()
[id:1; username:测试; password:sfasgfaf]
7.工具类
MyBatisUtil.java
package com.tiantian.base; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil {public static SqlSessionFactory getSqlSessionFactory() {String resource = "mybatis-config.xml"; // 使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource); // 构建sqlSession的工厂SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); return sessionFactory; }public static SqlSession getSqlSession() {return getSqlSessionFactory().openSession(); }public static SqlSession getSqlSession(boolean isAutoCommit) {return getSqlSessionFactory().openSession(isAutoCommit); }}
【mybatis|mybatis @Intercepts的用法解读】以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
推荐阅读
- 热闹中的孤独
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 放屁有这三个特征的,请注意啦!这说明你的身体毒素太多
- 一个人的旅行,三亚
- 布丽吉特,人生绝对的赢家
- 慢慢的美丽
- 尽力
- 一个小故事,我的思考。
- 家乡的那条小河
- 《真与假的困惑》???|《真与假的困惑》??? ——致良知是一种伟大的力量