SimpleJdbcTemplate批量更新(BeanPropertySqlParameterSource)



用SimpleJdbcTemplate实现批量新增和批量修改。

1)使用BeanPropertySqlParameterSource。

BeanPropertySqlParameterSource的父类实现了SqlParameterSource接口。 

为了方便理解,我将实现过程,访问数据库放在一个类的一个方法中。

即使堆砌成山的代码,其思路有可能却是简单的。

 1 import java.util.ArrayList;
2 import java.util.List;
3
4 import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
5 import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
6
7 import com.dto.mc.UserDto;
8
9 public class TestBeanPropertySqlParameterSource extends SimpleJdbcDaoSupport{
10 private void batchUpdate4User(List<UserDto> userDtoList) throws Exception {
11     //将userDtoList转化成BeanPropertySqlParameterSource[]数组
12 List<BeanPropertySqlParameterSource> userSourceList = new ArrayList<BeanPropertySqlParameterSource>();
13 for (UserDto userDto : userDtoList) {
14 userSourceList.add(new BeanPropertySqlParameterSource(userDto));
15 }
16 BeanPropertySqlParameterSource[] beanSources = userSourceList.toArray(new BeanPropertySqlParameterSource[userSourceList.size()]);
17
18 //userDto修改的字段与数据库的字段必须满足映射条件。
19 StringBuffer sql = new StringBuffer();
20 sql.append("update user set nickName = :nickName, update_time = :updateTime,")
21 .append(" update_userName = :updateUserName where userId = :userId");
22
23 this.getSimpleJdbcTemplate().batchUpdate(sql.toString(), beanSources);
24 }
25 }

2)使用SqlParameterSourceUtils.createBatch(list.toArray())

1     public void saveModifiedVendorTemp(List<UserDto> list) throws Exception
2 {
3 StringBuffer sql = new StringBuffer();
4 sql.append(" update user_ys set role = :role where userId = :userId");
5 this.getSimpleJdbcTemplate()
6 .batchUpdate(sql.toString(), SqlParameterSourceUtils.createBatch(list.toArray()));
7 }

源代码:org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils.createBatch方法

同样将数组转化成BeanPropertySqlParameterSource数组。

 1     /**
2 * * Create an array of BeanPropertySqlParameterSource objects populated
3 * with data * from the values passed in. This will define what is included
4 * in a batch operation. * @param beans object array of beans containing the
5 * values to be used * @return an array of SqlParameterSource
6 */
7 public static SqlParameterSource[] createBatch(Object[] beans) {
8 BeanPropertySqlParameterSource[] batch = new BeanPropertySqlParameterSource[beans.length];
9 for (int i = 0; i < beans.length; i++) {
10 Object bean = beans[i];
11 batch[i] = new BeanPropertySqlParameterSource(bean);
12 }
13 return batch;
14 }
原文地址:https://www.cnblogs.com/csuwangwei/p/2280794.html