標籤:
Mybatis 攔截器不做解釋了,用過的基本都知道,這裡用load data local主要是應對大批量資料的處理,提高效能,也支援交易回復,且不影響其他的DML操作,當然這個操作不要涉及到當前所load的資料,其中在使用的時候一定要local , 這個命令使用是mysql規定的,否則不加則會認為是伺服器本地的檔案。這裡主要是以流的方式來做處理,這樣可以使用記憶體流,這樣就可以避免在某些時候需要組建檔案才能匯入的多餘操作,和IO效能消耗。也可以是應用本地的檔案。
註:該做法只試用於存入資料的表,不試用於有頻繁更新,查詢操作的表。 因為load 命令的優先順序比更新命令,及查詢命令的優先順序低。
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 { @Override public 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) { // 如果不使用流的方式, 則會讀取語句中對應在本地的檔案 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); // 將流設定到執行語句中,在後續執行過程中,會忽略load data 語句中的檔案名稱,改用當前設定流 mysqlStatement.setLocalInfileInputStream((InputStream)in); invocation.getArgs()[0] = mysqlStatement; // 將當前語句執行代理,換成mysql的語句對象,方便下面執行。 } } } return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { } }
本文轉自:http://www.oschina.net/code/snippet_144320_24440#66175
Mybatis攔截器 mysql load data local 記憶體流處理