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()));
                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) {
            return resultOfUpdateOperation2();

Leave a Reply

Your email address will not be published. Required fields are marked *