Search code examples
javaspringspring-bootjdbctemplate

Update JdbcTemplate by jdbcTemplate.update(List)


I am using Spring Batch. How can I update all records in single database call?

@Autowired
private JdbcTemplate jdbcTemplate;

@Override
public void write(List<? extends Users> users) throws Exception {

    String updateQuery = "update users set ddp_created_fl=? where email=?";

    for(Users user:users) {
        jdbcTemplate.update(updateQuery, 1, user.getEmail());
    }
}

Solution

  • You can use batchUpdate to update all records in single database call.

    public void write(List<Users> users) throws Exception {
        String updateQuery = "update users set ddp_created_fl=? where email=?";
    
        jdbcTemplate.batchUpdate(updateQuery,
                    new BatchPreparedStatementSetter() {
    
                        public void setValues(PreparedStatement ps, int i) 
                            throws SQLException {
                            ps.setLong(1, 1);
                            ps.setString(2, users.get(i).getEmail());
                        }
    
                        public int getBatchSize() {
                            return users.size();
                        }
    
                    });
    }