MyBatis源码分析(三)批量更新

主要是org.apache.ibatis.executor.BatchExecutor这个类,此类继承BaseExecutor(基本增删改查,缓存,懒加载处理)
BatchExecutor这个类有四个属性

  //批处理更新最大返回结果 
public static final int BATCH_UPDATE_RETURN_VALUE = Integer.MIN_VALUE + 1002;
//存放声明(命令)对象集合
  private final List<Statement> statementList = new ArrayList<Statement>();
// 批处理结果集合
  private final List<BatchResult> batchResultList = new ArrayList<BatchResult>();
//当前sql语句
  private String currentSql;

 一个带参数构造函数,传入配置信息和事务对象

public BatchExecutor(Configuration configuration, Transaction transaction) {
super(configuration, transaction);
}

重写了三个方法, 1.更新方法  2.查询方法 3.刷新方法
我们来看批量更新doUpdate

public int doUpdate(MappedStatement ms, Object parameterObject)
throws SQLException {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null);
BoundSql boundSql = handler.getBoundSql();
String sql = boundSql.getSql();
Statement stmt;
if (currentSql != null && sql.hashCode() == currentSql.hashCode() && sql.length() == currentSql.length()) {
int last = statementList.size() - 1;
stmt = statementList.get(last);
} else {
Connection connection = transaction.getConnection();
stmt = handler.prepare(connection);
currentSql = sql;
statementList.add(stmt);
batchResultList.add(new BatchResult(ms, sql, parameterObject));
}
handler.parameterize(stmt);
handler.batch(stmt);
return BATCH_UPDATE_RETURN_VALUE;
}

  最重要一句话就是handler.batch(stmt),实际上就是stmt.addBatch();
举个小例子来说明:

//记录1
stmt.setInt(1, 1); 
stmt.setString(2, "Cujo"); 
stmt.addBatch(); 

//记录2
stmt.setInt(1, 2); 
stmt.setString(2, "Fred"); 
stmt.addBatch(); 

//记录3
stmt.setInt(1, 3); 
stmt.setString(2, "Mark"); 
stmt.addBatch(); 

//批量执行上面3条语句
int [] counts = statement.executeBatch(); 

//Commit it 
connection.commit();

 

如果项目中要用到批量更新如何使用?
下面的映射文件,假设namespace="com.dao.Stuent"

<insert id="insertbatch" parameterType="java.util.List"> 
<selectKey keyProperty="fetchTime" order="BEFORE" 
resultType="java.lang.String"> 
SELECT CURRENT_TIMESTAMP() 
</selectKey> 
insert into kangaiduoyaodian ( depart1, depart2, product_name, 
generic_name, img, product_specification, unit, 
approval_certificate, manufacturer, marketPrice, vipPrice, 
website, fetch_time, productdesc ) values 
<foreach collection="list" item="item" index="index" 
separator=","> 
( #{item.depart1}, #{item.depart2}, #{item.productName}, 
#{item.genericName}, #{item.img}, 
#{item.productSpecification}, #{item.unit}, 
#{item.approvalCertificate}, #{item.manufacturer}, 
#{item.marketprice}, #{item.vipprice}, #{item.website}, 
#{fetchTime}, #{item.productdesc} ) 
</foreach> 
</insert> 

 调用:  SqlSession session = factory.openSession(ExecutorType.BATCH); //关键是这句

原文: http://www.ibatis3.com/thread-111-1-1.html

你可能感兴趣的:(mybatis)