java批量更新数据库表中的数据


批量更新表中的id值,使用JdbcTemplate的批量更新方法

@Service("AsjUpdateServiceImpl")
public class AsjUpdateServiceImpl {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    AsjDao asjDao;
    public void asjBatchUpdate(final List<TGaXzXzxtAsj> asjs){
        String sql = "update T_GA_XZ_XZXT_ASJ set id = ? where ajbh = ?";
        int[] updateCounts = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ps.setString(1,asjs.get(i).getId());
                ps.setString(2,asjs.get(i).getAjbh());

            }
            public int getBatchSize() {
                return asjs.size();
            }
        });
        System.out.println("Records updated!");
    }

    /**
     * 案事件数据更新ID字段更新
     */
    public void  updateAsjId(int record) throws IOException {
        //初始化数据
        List<TGaXzXzxtAsj> initDatas = asjDao.getAsjIdNull(record);
        List<TGaXzXzxtAsj> asjs = new ArrayList<>();
        for(int i=0;i<initDatas.size();i++){
            TGaXzXzxtAsj tGaXzXzxtAsj = initDatas.get(i);
            tGaXzXzxtAsj.setId(RandomUtil.getUUID(32));
            asjs.add(tGaXzXzxtAsj);
            if (asjs.size()%5000==0){
                asjBatchUpdate(asjs);
                asjs.clear();
            }
        }
        if (asjs.size()!=0){
            asjBatchUpdate(asjs);
            asjs.clear();
        }
        initDatas.clear();
    }

}
@Repository
public interface AsjDao extends JpaRepository<TGaXzXzxtAsj,String> {
    /**
     * 获取表的sfzh,用于临时一些数据更新
     */
    @Query(value="SELECT * from T_GA_XZ_XZXT_ASJ where id is null and  rownum<=?",nativeQuery = true)
    List<TGaXzXzxtAsj> getAsjIdNull(int record);
}