Mybatis拦截器 mysql load data local 内存流处理
生活随笔
收集整理的這篇文章主要介紹了
Mybatis拦截器 mysql load data local 内存流处理
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Mybatis?攔截器不做解釋了,用過的基本都知道,這里用load?data?local主要是應(yīng)對(duì)大批量數(shù)據(jù)的處理,提高性能,也支持事務(wù)回滾,且不影響其他的DML操作,當(dāng)然這個(gè)操作不要涉及到當(dāng)前所load的數(shù)據(jù),其中在使用的時(shí)候一定要local?,?這個(gè)命令使用是mysql規(guī)定的,否則不加則會(huì)認(rèn)為是服務(wù)器本地的文件。這里主要是以流的方式來做處理,這樣可以使用內(nèi)存流,這樣就可以避免在某些時(shí)候需要生成文件才能導(dǎo)入的多余操作,和IO性能消耗。也可以是應(yīng)用本地的文件。
注:該做法只試用于存入數(shù)據(jù)的表,不試用于有頻繁更新,查詢操作的表。?因?yàn)閘oad?命令的優(yōu)先級(jí)比更新命令,及查詢命令的優(yōu)先級(jí)低。
mybatis 插件配置
<plugins><plugin interceptor="com.yunat.channel.process.util.LoadDataInterceptor"><property name="databaseType" value="mysql"/></plugin> </plugins>插入SQL
<select id="saveTest" parameterType="map">LOAD DATA LOCAL INFILE 'sql.csv' IGNORE INTO TABLE test (a,b,d) </select>插件代碼
package com.yunat.channel.process.util;import java.io.InputStream; import java.sql.Statement; import java.util.Properties;import org.apache.ibatis.executor.statement.RoutingStatementHandler; import org.apache.ibatis.executor.statement.StatementHandler; import org.apache.ibatis.mapping.BoundSql; 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;@Intercepts({ @Signature(method = "update", type = StatementHandler.class, args = { Statement.class }) }) public class LoadDataInterceptor implements Interceptor {@Overridepublic Object intercept(Invocation invocation) throws Throwable {RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget();BoundSql boundSql = handler.getBoundSql();if (boundSql.getSql().toLowerCase().contains("load data local infile")) {Object in = boundSql.getParameterObject();if (in != null && in instanceof InputStream) { // 如果不使用流的方式, 則會(huì)讀取語句中對(duì)應(yīng)在本地的文件Statement statement = (Statement) invocation.getArgs()[0];if (statement.isWrapperFor(com.mysql.jdbc.Statement.class)) {com.mysql.jdbc.PreparedStatement mysqlStatement = statement.unwrap(com.mysql.jdbc.PreparedStatement.class);// 將流設(shè)置到執(zhí)行語句中,在后續(xù)執(zhí)行過程中,會(huì)忽略load data 語句中的文件名,改用當(dāng)前設(shè)置流 mysqlStatement.setLocalInfileInputStream((InputStream)in);invocation.getArgs()[0] = mysqlStatement; // 將當(dāng)前語句執(zhí)行代理,換成mysql的語句對(duì)象,方便下面執(zhí)行。 }}}return invocation.proceed();}@Overridepublic Object plugin(Object target) {return Plugin.wrap(target, this);}@Overridepublic void setProperties(Properties properties) {}}本文轉(zhuǎn)自:http://www.oschina.net/code/snippet_144320_24440#66175
轉(zhuǎn)載于:https://www.cnblogs.com/dreammyle/p/5533504.html
總結(jié)
以上是生活随笔為你收集整理的Mybatis拦截器 mysql load data local 内存流处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: win 文字转化为语音
- 下一篇: MongoDB数据库安装与连接