spring boot 项目利用jdbc进行批量操作
有的需求会要求后端批量处理,因此可以用以下方式。
1.配置yml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/database
driver-class-name: com.mysql.jdbc.Driver
或者如下
spring:
datasource:
druid:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/database
driverClassName: com.mysql.jdbc.Driver
2.service 层执行业务关键代码
@Autowired
DataSource dataSource;
@Override
public BaseResponse updateBatchData(@Valid BaseRequest<T> req){
List<T> list = dao.queryData();
if(!CollectionUtils.isEmpty(list)) {
Connection connection = null;
Statement st = null;
try {
connection = dataSource.getConnection();
st = connection.createStatement();
connection.setAutoCommit(false);
for(int i = 0; i < list.size(); i++) {
st.executeUpdate("update tb set word='123' where id=1");
if((i+1)%100 == 0) {
connection.commit();
System.out.println("完成100条数据的提交.");
}
}
connection.commit();
}catch(Exception e) {
e.printStackTrace();
}finally {
if(null != st) {
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null != connection) {
try {
connection.setAutoCommit(true);
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return new BaseResponse();
}