织梦网站首页,怎样做模板网站,wordpress plugin 开发,西安排名seo公司专栏精选
引入Mybatis
Mybatis的快速入门
Mybatis的增删改查扩展功能说明
mapper映射的参数和结果
Mybatis复杂类型的结果映射
Mybatis基于注解的结果映射
Mybatis枚举类型处理和类型处理器
再谈动态SQL
Mybatis配置入门
Mybatis行为配置之Ⅰ—缓存
Mybatis行为配置…专栏精选
引入Mybatis
Mybatis的快速入门
Mybatis的增删改查扩展功能说明
mapper映射的参数和结果
Mybatis复杂类型的结果映射
Mybatis基于注解的结果映射
Mybatis枚举类型处理和类型处理器
再谈动态SQL
Mybatis配置入门
Mybatis行为配置之Ⅰ—缓存
Mybatis行为配置之Ⅱ—结果相关配置项说明
Mybatis行为配置之Ⅲ—其他行为配置项说明
Mybatis行为配置之Ⅳ—日志
Mybatis整合Spring详解
Mybatis插件入门
Mybatis专栏代码资源 文章目录 专栏精选引言摘要正文SQL耗时插件分页插件 总结 引言
大家好我是奇迹老李一个专注于分享开发经验和基础教程的博主。欢迎来到我的频道这里汇聚了汇集编程技巧、代码示例和技术教程欢迎广大朋友们点赞评论提出意见重要的是点击关注喔 期待在这里与你共同度过美好的时光️。今天要和大家分享的内容是Mybatis插件。做好准备Let’s go
摘要
在这篇文章中我们将简单介绍Mybatis的插件开发了解插件的基本使用方法我将以计算sql耗时、分页查询两个简单的插件为例带领大家领略Mybatis插件的魅力。准备好开启今天的神奇之旅了吗
正文 Mybatis中也提供了插件的功能虽然叫插件但是实际上是通过拦截器Interceptor实现的。在MyBatis的插件模块中涉及责任链模式和JDK动态代理 –《Mybatis技术内幕徐郡明 编著》 在mybatis项目中通过实现 org.apache.ibatis.plugin.Interceptor接口可以定义一个拦截器重写 intercept()方法来定义拦截器的具体操作。同时通过 org.apache.ibatis.plugin.Intercepts和 org.apache.ibatis.plugin.Signature注解定义需要被拦截的位置类和方法。常见的插件如分库分表、自动分页、数据脱敏、加密解密等等
下面以两个简单的例子说明拦截器的具体实现
SQL耗时插件
Intercepts({Signature(type StatementHandler.class, method query, args {Statement.class, ResultHandler.class}),Signature(type StatementHandler.class, method update, args {Statement.class}),Signature(type StatementHandler.class, method batch, args {Statement.class})
})
public class SqlCostTimeInterceptor implements Interceptor {private static Logger logger LoggerFactory.getLogger(SqlCostTimeInterceptor.class);Overridepublic Object intercept(Invocation invocation) throws Throwable {Object target invocation.getTarget();long startTime System.currentTimeMillis();StatementHandler statementHandler (StatementHandler) target;try {return invocation.proceed();} finally {long costTime System.currentTimeMillis() - startTime;BoundSql boundSql statementHandler.getBoundSql();String sql boundSql.getSql();logger.info(执行 SQL[ {} ]执行耗时[ {} ms], sql, costTime);}}Overridepublic Object plugin(Object target) {return Plugin.wrap(target, this);}Overridepublic void setProperties(Properties properties) {System.out.println(插件配置的信息properties);}
}!-- MyBatis全局配置文件mybatis-config.xml --
pluginsplugin interceptorcom.xzg.cd.a88.SqlCostTimeInterceptorproperty namesomeProperty value100//plugin
/plugins分页插件
mybatis分页的详细实现思路可参考 MyBatis分页插件PageHelper项目
实现思路如下
拦截 org.apache.ibatis.executor.Executor#query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler)方法获取到rowBounds参数中的offset和limit获取到 MappedStatement参数中的sql语句并根据上一步中的分页参数重新构建分页sql使用上一步生成的分页sql语句构建新的MappedStatement替换原有 MappedStatement执行查询操作
代码如下
package top.sunyog.mybatis.plugins; 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.Signature;
import org.apache.ibatis.session.Configuration;
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 PageHelperInterceptor implements Interceptor { private final int STATEMENT_ARG_INDEX 0; private final int PARAMETER_ARG_INDEX 1; private final int ROWBOUND_ARG_INDEX 2; Override public Object intercept(Invocation invocation) throws Throwable { Object[] args invocation.getArgs(); //获取待查sql MappedStatement ms (MappedStatement) args[STATEMENT_ARG_INDEX]; Object parameter args[PARAMETER_ARG_INDEX]; BoundSql sql ms.getBoundSql(parameter); String sqlStr sql.getSql().trim(); //获取分页内容 RowBounds rowBounds (RowBounds) args[ROWBOUND_ARG_INDEX]; int limit rowBounds.getLimit(); int offset rowBounds.getOffset(); //重新拼接sql StringBuffer buffer new StringBuffer(sqlStr.length() 100); buffer.append(select t.* from (); buffer.append(sqlStr); buffer.append() t limit ).append(offset).append(, ).append(limit); //创建新的statement Configuration config ms.getConfiguration(); BoundSql newBoundSql new BoundSql(config, buffer.toString(), sql.getParameterMappings(), parameter); SqlSource sqlSource o - newBoundSql; //按照原有ms生成新ms MappedStatement.Builder builder new MappedStatement.Builder(config, ms.getId(), sqlSource, ms.getSqlCommandType()); builder.resource(ms.getResource()) .fetchSize(ms.getFetchSize()) .statementType(ms.getStatementType()) .keyGenerator(ms.getKeyGenerator()) .timeout(ms.getTimeout()) .parameterMap(ms.getParameterMap()) .resultMaps(ms.getResultMaps()) .resultSetType(ms.getResultSetType()) .cache(ms.getCache()) .flushCacheRequired(ms.isFlushCacheRequired()) .useCache(ms.isUseCache()); //替换原来的ms args[STATEMENT_ARG_INDEX] builder.build(); //替换原来的rowBound RowBounds newRowBounds new RowBounds(RowBounds.NO_ROW_OFFSET, RowBounds.NO_ROW_LIMIT); args[ROWBOUND_ARG_INDEX] newRowBounds; return invocation.proceed(); } Override public Object plugin(Object target) { return Interceptor.super.plugin(target); } Override public void setProperties(Properties properties) { Interceptor.super.setProperties(properties); }
}配置文件中添加插件配置注意mybatis配置文件中标签的顺序
?xml version1.0 encodingUTF-8 ?
!DOCTYPE configuration PUBLIC -//mybatis.org//DTD Config 3.0//EN https://mybatis.org/dtd/mybatis-3-config.dtd
configuration properties resourcemysql-env.properties property nametest-key valuetest-value-c/ /properties settings.../settingstypeAliases.../typeAliases typeHandlers.../typeHandlersplugins plugin interceptortop.sunyog.mybatis.plugins.PageHelperInterceptor/ /pluginsenvironments.../environmentsmappers.../mappers
/configuration测试代码如下
private void testListPage(){ SqlSession sqlSession MybatisAppContext.getSqlSessionFactory().openSession(); final String statementtop.sunyog.mybatis.mapper.LessonMapper.getDemos; //调用被拦截的方法sqlSession.select(statement, null, new RowBounds(0, 1), new ResultHandler() { Override public void handleResult(ResultContext resultContext) { Object obj resultContext.getResultObject(); System.out.println(obj); } }); sqlSession.close();
}查询打印结果如下数据库中有多条记录
TestDemo{demoId1, demoName测试名称, demoDesc测试备注}在mybatis插件中可以拦截的方法如下
Executor类中的update()、query()、flushStatements()、commit()、rollback()、getTransaction()、close()、isClosed()方法ParameterHandler类中的getParameterObject()、setParameters()方法ResultSetHandler类中的handleResultSets()、handleOu飞putParameters()方法StatementHandler类中的prepare()、parameterize()、batch()、update()、query()方法。
总结
Mybatis中的插件实际上就是一个拦截器Mybatis通过拦截器链来保证每个注册的插件功能都能顺利调用而且Mybatis通过Signature注解为我们提供了丰富的可拦截方法为编写功能丰富的Mybatis扩展创造了条件。当然想要编写优秀的Mybatis插件还需要对Mybatis的实现原理有更加深入的了解。
到本章为止关于Mybatis专栏的基础入门相关知识就介绍完了感谢大家的观看谢谢 联系方式 邮箱qijilaolifoxmail.com ❗版权声明 本文为原创文章版权归作者所有。未经许可禁止转载。更多内容请访问奇迹老李的博客首页