Mixer
Mixer

Reputation: 359

Mixing PreparedStatement batch with Statement batch, is it possible?

Is it possible to mix somehow PreparedStatement batch with Statement batch and keep benefits of both executed in a single transaction?

What I have is my own Data Access Object which represents transaction. I want to use it like this:

/* here transaction starts: object receive connection, etc. */
MyTableTransactionObject myTable = new MyTableTransactionObject();

myTable.clear();
myTable.insert(Row1);
myTable.insert(Row2);
myTable.insert(Row3);
myTable.doSomethingElse();
myTable.insert(Row4);

/* here transaction ends, batches are executed changes are commited,
   statements are closed */
myTable.execute();
myTable.close();

"Under the hood" of MyTableTransactionObject there are methods using Statement or PreparedStatements (there may be multiple PreparedStatements). For example: in clear() method I want to use statement.addBatch("DELETE FROM table;"), in insert(...) method I want to use special PreparedStatement to perform SQL INSERT operation, in doSomethingElse(...) I want to use different PreparedStatement for something else, etc.

How can I achieve execution of this statements in order they were called on myTable.execute()?

Upvotes: 1

Views: 1068

Answers (2)

adv
adv

Reputation: 357

This is not the most elegant solution, and you will pay out of the %$# in performance, but it does work.

public class DBEngine {

private final int defaultBatchSize = 1000;

private Pool pool = null;
private Connection con = null;
private PreparedStatement ps = null;
private ArrayList<PreparedStatement> globalBatch = new ArrayList<PreparedStatement>();
private int k = 0;  //bean-wide batch counter
private boolean debugMode = false;
private PreparedStatement batchPs = null;
//--------------------------------
DBEngine(){
    this.pool = new Pool();
    this.con = pool.getConnection();
    this.ps = null;
    this.k = 0;  //bean-wide batch counter
}
//-------------
boolean mixedBatchTime(boolean force){
    return mixedBatchTime(defaultBatchSize, force);
}
//-------------
boolean mixedBatchTime(int customBatchSize){
    return mixedBatchTime(customBatchSize, false);
}
//-------------
boolean mixedBatchTime(){
    return mixedBatchTime(defaultBatchSize, false);
}
//-------------
// Executes a mixed batch of PreparedStatements
//-------------
boolean mixedBatchTime(int customBatchSize, boolean force){


    if(k > customBatchSize - 1 || force){
        try {
            StringBuilder sqlStmt = new StringBuilder();

            for(int i = 0; i < globalBatch.size(); i++){
                sqlStmt.append(globalBatch.get(i) + "; ");
            }

            batchPs = con.prepareStatement(sqlStmt.toString());    
            batchPs.execute();
            ps = null;
            sqlStmt = null;
            batchPs = null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        k = 0;
        globalBatch = null;
        globalBatch = new ArrayList<PreparedStatement>();
        return true;
    }else return false;

  }
}

You have to increment k in your actual batch preparation section that is inside of your DBEngine bean like:

    //------------------------------------------
     boolean updateSomeQuantity(int someID, int someQuantity){

        try{
            // detects if the statement has changed in order to recompile it only once per change 
            if(ps!=null && !ps.toString().contains("UPDATE sometable SET somequantity =")){
                ps = null;
                String updateStmt = "UPDATE sometable SET somequantity = ? WHERE someID = ?";
                ps = con.prepareStatement(updateStmt);
            }else if(ps == null){
                String updateStmt = "UPDATE sometable SET somequantity = ? WHERE someID = ?";
                ps = con.prepareStatement(updateStmt);
            }

            ps.setInt(1, someQuantity)
            ps.setInt(2, someID);

            globalBatch.add(ps);
            k++;   // very important

            return true;

        } catch (SQLException e) {
            e.printStackTrace();
            if(e.getNextException() != null) e.getNextException().printStackTrace();
            return false;
          }
    }

The actual implementation is in another code in which you instantiate an instance of the DBEngine bean and use the updateSomeQuantity(somequantity) method along with the mixedBatchTime() method in a loop. After the loop is finished, call a mixedBatchTime(true) to batch whatever is leftover.

NOTE: This solution uses AutoCommit(true)

Upvotes: 1

jtahlborn
jtahlborn

Reputation: 53694

if your Statements/PreparedStatements share a common Connection and you don't commit the transaction on that Connection, then they will share a common transaction.

Upvotes: 0

Related Questions