Java : Cancel failed insert using Hibernate

时间:2018-03-19 13:38:04

标签: java hibernate

I'm looking for a way to cancel a failed insert, using Hibernate.

Context : I've got a program which has to format and then transfer data from a source database to a destination Oracle database. Since i've got a lot of data to process, I want to be able to insert in bulks (ex: 100 rows bulks). But the thing is, sometimes an insert could fail because of a bad format (typically, trying to insert a 50 characters long string in a field that can only take up to 32). I could bypass the problem by checking first if the row is valid before trying to insert it, but I'm looking for another way to do it.

I tried to do something like this :

List<MyDataObject> dataList=processData();
HibernateUtils myUtils=HibernateUtils.getInstance();
myUtils.openTransaction(); //opens the transaction so it is not automatically committed after every insert
int i=0;
for(MyDataObject data:dataList){
    myUtils.setSavepoint(); //Creates a savepoint
    try{
        myUtils.insertData(data); //Does not commit, but persists the data object into the DB
        myUtils.flush();
    } catch (RuntimeException e){
        myUtils.rollbackSavepoint(); //Rolls back to the savepoint I created right before inserting the last element
        myUtils.commitTransaction();
        i=0;
        continue;
    }
    if(++i==100){
        myUtils.commitTransaction();
        i=0;
    }
}
myUtils.closeTransaction();

However, it doesn't work because the unflushed, failed insert will not be rolled back even though I rolled back to the savepoint I created before inserting, probably because it wasn't actually flushed in the first place (because flushing throws an error because of the bad format).

My savepoint rollback is working, if I throw a "fake" runtimeException after inserting some element, this last element won't be in the database

How can I bypass the problem ? (I'd like a way to delete the unflushed SQL instructions while keeping the flushed ones in the transaction)

Thank you in advance for any help

0 个答案:

没有答案