日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

你所不知道的mybatis居然也有拦截器

發(fā)布時(shí)間:2025/3/15 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 你所不知道的mybatis居然也有拦截器 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

對于mybatis的攔截器這個(gè)想法我來自于三個(gè)地方

也就是下面這個(gè)三個(gè)地方是可以使用的,其他的情況需要開發(fā)人員根據(jù)實(shí)際情況來使用。

1、對于分頁的查詢,我們可以對于分頁的方法采用比較規(guī)范的命名,然后根據(jù)這個(gè)命名來攔截需要分頁查詢的sql然后把分頁的總數(shù),分頁數(shù),頁碼數(shù),頁碼總數(shù)等放在一個(gè)對象中返回去,這樣分頁只要調(diào)用dao的一個(gè)方法即可。

2、讀寫分離,我們可以在sql執(zhí)行之前,獲取sql是不是查詢方法,然后根據(jù)這個(gè)條件去控制需要訪問的數(shù)據(jù)源。

3、需要統(tǒng)計(jì)分析sql的執(zhí)行時(shí)間(這邊要說的是這里的執(zhí)行包含了網(wǎng)絡(luò)帶寬,因?yàn)椴皇窃趍ysql執(zhí)行前后做的攔截,所以這里的sql并不只是sql在數(shù)據(jù)庫真正執(zhí)行的時(shí)間,要比實(shí)際長)

?

如何實(shí)現(xiàn)這樣一個(gè)攔截器

首先mybatis官方早就想到我們開發(fā)會有這樣的需求,所以開放了一個(gè)org.apache.ibatis.plugin.Interceptor這樣一個(gè)接口。

我們只要實(shí)現(xiàn)這個(gè)接口并且加上注解然后重寫intercept方法。

最后如果你使用的是mybatis.xml也就是mybatis本身單獨(dú)的配置,你可以需要在這里配置相應(yīng)的攔截器名字等。

如果你使用的是spring管理的mybatis,那么你需要在spring配置文件里面配置注冊相應(yīng)的攔截器。

?

代碼實(shí)現(xiàn)

下面對于3,也就是實(shí)現(xiàn)統(tǒng)計(jì)sql執(zhí)行時(shí)間,簡單摘錄一下實(shí)現(xiàn)代碼。

還有兩種開發(fā)可以根據(jù)自己的想法去實(shí)現(xiàn)和摸索。

package com.ssm;import java.text.DateFormat; import java.util.Date; import java.util.List; import java.util.Locale; 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.ParameterMapping; 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.reflection.MetaObject; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.type.TypeHandlerRegistry; import org.apache.log4j.Logger;@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 SqlStatementInterceptor implements Interceptor{ private static Logger logger = Logger.getLogger(SqlStatementInterceptor.class); @SuppressWarnings("unused") private Properties properties; @Override public Object intercept(Invocation arg0) throws Throwable { MappedStatement mappedStatement = (MappedStatement) arg0.getArgs()[0]; Object parameter = null; if (arg0.getArgs().length > 1) { parameter = arg0.getArgs()[1]; } String sqlId = mappedStatement.getId(); BoundSql boundSql = mappedStatement.getBoundSql(parameter); Configuration configuration = mappedStatement.getConfiguration(); Object returnValue = null; long start = System.currentTimeMillis(); returnValue = arg0.proceed(); long end = System.currentTimeMillis(); long time = (end - start); if (time > 1) { String sql = getSql(configuration, boundSql, sqlId, time); logger.error(sql);} return returnValue; } public static String getSql(Configuration configuration, BoundSql boundSql, String sqlId, long time) { String sql = showSql(configuration, boundSql); StringBuilder str = new StringBuilder(100); str.append(sqlId); str.append(":"); str.append(sql); str.append(":"); str.append(time); str.append("ms"); return str.toString(); } public static String showSql(Configuration configuration, BoundSql boundSql) { Object parameterObject = boundSql.getParameterObject(); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); String sql = boundSql.getSql().replaceAll("[\\s]+", " "); if (parameterMappings.size() > 0 && parameterObject != null) { TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { sql = sql.replaceFirst("\\?", getParameterValue(parameterObject)); } else { MetaObject metaObject = configuration.newMetaObject(parameterObject); for (ParameterMapping parameterMapping : parameterMappings) { String propertyName = parameterMapping.getProperty(); if (metaObject.hasGetter(propertyName)) { Object obj = metaObject.getValue(propertyName); sql = sql.replaceFirst("\\?", getParameterValue(obj)); } else if (boundSql.hasAdditionalParameter(propertyName)) { Object obj = boundSql.getAdditionalParameter(propertyName); sql = sql.replaceFirst("\\?", getParameterValue(obj)); } } } } return sql; } private static String getParameterValue(Object obj) { String value = null; if (obj instanceof String) { value = "'" + obj.toString() + "'"; } else if (obj instanceof Date) { DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA); value = "'" + formatter.format(new Date()) + "'"; } else { if (obj != null) { value = obj.toString(); } else { value = ""; } } return value; } @Override public Object plugin(Object arg0) { return Plugin.wrap(arg0, this); } @Override public void setProperties(Properties arg0) { this.properties = arg0; } }

下面是spring中的配置,如果你是單獨(dú)配置mybatis配置文件的話,你需要查詢一下如何配置

<!-- 配置mybitasSqlSessionFactoryBean --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="typeAliasesPackage" value="com/ssm/entity"></property><property name="mapperLocations" value="classpath*:com/ssm/dao/sqlxml/*.xml"></property><property name="plugins"><array><bean class="com.ssm.SqlStatementInterceptor"><property name="properties"><value>property-key=property-value</value></property></bean></array></property></bean>

會在log日志中輸出最后執(zhí)行的sql和sqlID和sql執(zhí)行的時(shí)間。

?

?

參考資料:

分頁實(shí)現(xiàn)(本人沒有親自實(shí)現(xiàn),因?yàn)楝F(xiàn)實(shí)情況還沒有這樣特別需要這樣的業(yè)務(wù)邏輯):

http://www.cnblogs.com/jethypc/p/5149183.html

執(zhí)行時(shí)間統(tǒng)計(jì)實(shí)現(xiàn)(我修改了其中spring的配置,不知為何下面博主的配置并沒有用):

http://blog.csdn.net/tq02h2a/article/details/50772652

讀寫分離實(shí)現(xiàn)(其中的第四種方案就是利用了攔截器):

http://www.jianshu.com/p/2222257f96d3

轉(zhuǎn)載于:https://www.cnblogs.com/linkstar/p/6039513.html

新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎(jiǎng)!定制產(chǎn)品紅包拿不停!

總結(jié)

以上是生活随笔為你收集整理的你所不知道的mybatis居然也有拦截器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。