`
guanpanpan
  • 浏览: 16714 次
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

代码实例-设计模式-回调方式使用模板方法

 
阅读更多

批量更新数据


/**
 * 批量更新数据
 * @author guanpanpan
 *
 * @param <T>
 */
public abstract class BatchUpdate<T> {
	public final static Logger log = LoggerFactory.getLogger(BatchUpdate.class);

	public void execute(DB db, Collection<T> datas) throws SQLException {
		if (datas == null || datas.size() == 0) {
			return;
		}
		int dealSize = 0;
		try {
			db.startTranAndBatch();
			for (T data : datas) {
				updateToDb(db, data);
				dealSize++;
				if (dealSize >= DcConst.BANTCH_COMIT_SIZE) {
					dealSize = 0;
					db.exeBatchAndCommitTrans();
				}
			}
			if (dealSize > 0) {
				db.exeBatchAndCommitTrans();
			}

		} 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(DB db, T data) throws SQLException;
}

 

		new BatchUpdate<Integer>() {
			@Override
			public void updateToDb(DB db, Integer data) throws SQLException {
				Map<String, Object> parameterMap = new HashMap<String, Object>();
				parameterMap.put("id", data);
				parameterMap.put("oldTaskStatus", oldStatus);
				parameterMap.put("taskStatus", newStatus);
				db.getSqlMapClient().update("ChangeLog.updateChangeLogStatusById", parameterMap);
			}
		}.execute(getDb(dbNo), ids);

 

 

其它相关代码(ibatis-SqlMapClient client)

	public void startTranAndBatch() throws SQLException {
		client.startTransaction();
		client.startBatch();
	}
	public void exeBatchAndCommitTrans() throws SQLException {
		client.executeBatch();
		client.commitTransaction();
	}
	public void endTransaction() throws SQLException {
		client.endTransaction();
	}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics