Search code examples
activejdbc

ActiveJDBC batch insert and transaction


What is the recommended way to insert a batch of records or none if the database raises an error for any of the inserts? Here is my current code:

PreparedStatement ps = Base.startBatch("INSERT INTO table(col1) VALUES(?)");
for (MyModel m : myModels)
    Base.addBatch(ps, m.getCol1());
Base.executeBatch(ps);
ps.close();

This inserts records until the first one that fails (if happens).
I want all or nothing to be inserted, then I was thinking of wrapping the executeBatch():

Base.openTransaction();
Base.executeBatch(ps);
Base.commitTransaction();

If it is correct, should I do Base.rollbackTransaction() in some try catch?
Should I also close the ps.close() in a finally block?

Thanks!


Solution

  • Transacted batch operations are not any different from non-batch operations. Please, see this: http://javalite.io/transactions#transacted-activejdbc-example for a typical pattern.

    You will do this then:

    List<Person> myModels = new ArrayList<>();
        try{
            Base.openTransaction();
            PreparedStatement ps = Base.startBatch("INSERT INTO table(col1) VALUES(?)");
            for (Person m : myModels){
                Base.addBatch(ps, m.getCol1());
            }
            Base.executeBatch(ps);
            ps.close();
            Base.commitTransaction();
        }catch(Exception e){
            Base.rollbackTransaction();
        }
    

    This way, your data is intact in case of exceptions