30. 代码实例-设计模式-回调方式使用模板方法
1)模板类
package com.jd.consume.dao.mysql; import java.sql.SQLException; import java.util.Collection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ibatis.sqlmap.client.SqlMapClient; /** * 批量更新数据 * @author guanpanpan * * @param <T> */ public abstract class BatchUpdate<T> { public final static Logger log = LoggerFactory.getLogger(BatchUpdate.class); public static int BANTCH_COMIT_SIZE = 1000; public void execute(SqlMapClient db, Collection<T> datas) throws SQLException { if (datas == null || datas.size() == 0) { return; } int dealSize = 0; try { db.startTransaction(); db.startBatch(); for (T data : datas) { updateToDb(db, data); dealSize++; if (dealSize >= BANTCH_COMIT_SIZE) { dealSize = 0; db.executeBatch(); db.commitTransaction(); } } if (dealSize > 0) { db.executeBatch(); db.commitTransaction(); } } catch (SQLException e) { log.error("updatedatas To Db error:", e); throw e; } finally { try { db.endTransaction(); } catch (SQLException e) { e.printStackTrace(); } } } public abstract void updateToDb(SqlMapClient db, T data) throws SQLException; }
(2)使用模板类
new BatchUpdate<ConsumeDetail>() {
@Override
public void updateToDb(SqlMapClient db, ConsumeDetail ConsumeDetail) throws SQLException {
db.update("ConsumeDetailMysql.insertOrUpdateConsumeDetailWithId", ConsumeDetail);
}
}.execute(dbManager.getSqlMapClientTemplate(dbNo).getSqlMapClient(), ConsumeDetails);
注:本示例来源于consume-grade-final(mysql版本)
减少重复学习,在原来掌握的基础上进行提高。质疑驱动,不断对已经掌握的知识进行质疑。
如果能把已经掌握的东西总结成模式,才是真正掌握了。
浙公网安备 33010602011771号