在JdbcTemplate中执行批处理操作,可以通过以下步骤进行:
- 添加Maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
- 定义数据源和JdbcTemplate:
@Bean
public DataSource dataSource() {
return new DriverManagerDataSource(url, username, password);
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
- 编写批处理方法:
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void batchInsertUser(List<User> users) {
jdbcTemplate.batchUpdate("INSERT INTO user (name, age) VALUES (?, ?)",
new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
User user = users.get(i);
ps.setString(1, user.getName());
ps.setInt(2, user.getAge());
}
public int getBatchSize() {
return users.size();
}
}
);
}
}
- 实现
BatchPreparedStatementSetter
接口,在setValues()
方法中设置SQL语句的参数值。 - getBatchSize()方法返回批量更新的记录条数。
- jdbcTemplate.batchUpdate()执行批量更新操作。
4. 在Service层调用:
@Service
public class UserService {
@Autowired
private UserDao userDao;
public void saveUsers(List<User> users) {
userDao.batchInsertUser(users);
}
}
- 在Controller层接收请求并调用:
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/saveUsers")
public void saveUsers(@RequestBody List<User> users) {
userService.saveUsers(users);
}
}