用SimpleJdbcTemplate实现批量新增和批量修改。
1)使用BeanPropertySqlParameterSource。
BeanPropertySqlParameterSource的父类实现了SqlParameterSource接口。
为了方便理解,我将实现过程,访问数据库放在一个类的一个方法中。
即使堆砌成山的代码,其思路有可能却是简单的。
2)使用SqlParameterSourceUtils.createBatch(list.toArray())
源代码:org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils.createBatch方法
同样将数组转化成BeanPropertySqlParameterSource数组。
/* * (non-Javadoc) * * @see * com.bitbao.cm.dao.VerificationDao#addBatchVerificationItem(java.util. * List) */ @Override public boolean addBatchVerificationItem(List<VerificationContentVO> itemList) { DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("addBatchVerificationItem"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus txStatus = this.txManager.getTransaction(def); try { for (VerificationContentVO map : itemList) { this.namedJdbcTemplate.update(SQL_INSERT, mappingParameter(map)); } } catch (Exception e) { txManager.rollback(txStatus); CMLog.error("Exception to save verification", e); return false; } finally { txManager.commit(txStatus); } return true; } @SuppressWarnings("unchecked") public RowMapper mappingResult(Class<?> resultBean) { return new BeanPropertyRowMapper(resultBean); }