In our application, we have a few use cases where we need to update a lot of entries in a database table. We have a DataAccess object that we use for interacting with the database.
The code for updating looks like this.
String updateQuery = "UPDATE tbl SET column1=? WHERE column2=?";
for(i=0;;i++){
Map<Integer, Object> params=new HashMap<Integer, Object>();
params.put(1,"val"+i);
params.put(2,"val"+i);
DataAccess.addBatchParams(updateQuery,params);
}
DataAccess.executeBatch(updateQuery);
Inside DataAccess.addBatchParams(..)
public void addBatchParams(String query, Map<Integer,Object> params){
.. // preparedStatements contains all params passed till now.
..
if(preparedStatements.size() >= BATCH_SIZE){
executeBatch(query);
//flush preparedStatements as it has been written to db
}
..
..
}
My concern is that, whenever a new developer uses this, there is no way for him to know that he has to call executeBatch() method at the end of every batch update for flushing out the last few entries lesser than BATCH_SIZE to the db. Is there any better way to do this? Is there any design pattern or something for doing a database batch update?
Any help is appreciated.
Consolidate both methods together and make the
addBatchParamsandexecuteBatchmethods private.