简体   繁体   中英

Spring user transaction with hibernate

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?

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();
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM