views:

488

answers:

1

I want to control hibernate transaction myself so I can rollback at any time. I calling a thread to do business but not waiting for it to finish its job and update DB. This update is only available when the method ends but I want to commit changes in each for loop so I need to control hibernate transaction.

My Sample code is below:

for(BaseFileprocess fileProcess : unprocessedFiles) {
   BaseFileprocessfunctype functionType = fileProcessFunctionTypeService.findBySerno(fileProcess.getFunctioncodeserno());
   if(functionType != null) {
    taskExecutor.execute(new ServiceCallThread(functionType.getFunctionname(), fileProcess.getSerno(), fileProcess.getFilename()));
    fileProcess.setStatu("1");
    fileProcessService.update(fileProcess);//I need commit here
   }
   else {
    System.out.println("There is no defined Function Type");
   }
  }

Any suggestion?

+2  A: 

Look into Spring's transactionTemplate. From the docs:

// single TransactionTemplate shared amongst all methods in this instance
private final TransactionTemplate transactionTemplate;

// use constructor-injection to supply the PlatformTransactionManager
public SimpleService(PlatformTransactionManager transactionManager) {
    Assert.notNull(transactionManager, "The 'transactionManager' argument must not be null.");
    this.transactionTemplate = new TransactionTemplate(transactionManager);
}

public Object someServiceMethod() {
    return transactionTemplate.execute(new TransactionCallback() {

        // the code in this method executes in a transactional context
        public Object doInTransaction(TransactionStatus status) {
            updateOperation1();
            return resultOfUpdateOperation2();
        }
    });
}
Rich Kroll
Thank you. Transaction Template is suitable for me.
Firstthumb