利用Spring JdbcTemplate实现批量操作

/**
 * 更新资源与菜单的关系
 * @param operator
 * @param menuId
 * @param resourceIdList
 */
public void updateRelationshipWithMenu(final String operator, final String menuId, final List<String> resourceIdList) {
	/*
	 * 清除操作资源与指定功能模块菜单的关系
	 * 1.去除关联关系
	 * 2.去除排序编号
	 * 3.更新最后修改人,最后修改时间
	 */
	String clearSql = "UPDATE pf_resource SET menu_id = ?, resource_order = null, last_modify_by = ?, last_modify_time = ? WHERE menu_id = ?";
	jdbcTemplate.update(clearSql, new Object[] { null, operator,
			new Timestamp(Calendar.getInstance().getTime().getTime()), menuId });

	/*
	 * 重新建立操作资源与指定功能模块菜单的关系
	 * 1.建立关联关系
	 * 2.设置排序编号
	 * 3.更新最后修改人,最后修改时间
	 */
	String associateSql = null;
	if (resourceIdList.size() > 0) {
		/*获取菜单编码*/
		final String menuCode = menuDao.queryMenuCodeById(menuId);
		associateSql = "UPDATE pf_resource SET menu_id = ?, resource_order = ? , last_modify_by = ?, last_modify_time = ? WHERE id = ?";

		final long modifyTime = Calendar.getInstance().getTime().getTime();

		//批量更新
		jdbcTemplate.batchUpdate(associateSql, new BatchPreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				ps.setString(1, menuId);
				ps.setString(2, menuCode + "-" + (i + 1));
				ps.setString(3, operator);
				ps.setTimestamp(4, new Timestamp(modifyTime));
				ps.setString(5, resourceIdList.get(i));
			}

			@Override
			public int getBatchSize() {
				return resourceIdList.size();
			}
		});
	}
}

猜你喜欢

转载自edisonlv2010.iteye.com/blog/1872166