0

In the following Service, I am calling testBatch() from the controller, in testBatch() I am implementing batch saving. But when I am throwing RuntimeException. It is now rolling back. I have also defined rollBackFor in the @Transactional annotation. Data is always getting updated. But the expected behavior is to don't update anything in DB.


import com.example.test.testdb.entity.Expense;
import com.example.test.testdb.repository.ExpenseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class ExpenseService {

    @Autowired
    private ExpenseRepository expenseRepository;

    public Expense getExpense(Long id) {
        return expenseRepository.findById(id).get();
    }

    public Expense saveExpense(Expense expense) {
        return expenseRepository.save(expense);
    }

    public void testBatch() {
        List<Expense> expenses = expenseRepository.findAll();
        int batchSize = 5;

        for (int i = 0; i < expenses.size(); i++) {
            int start = i;
            int end = Math.min(i + batchSize, expenses.size() - 1);
            i = end;

            try {
                getNameString(expenses, start, end);
            } catch (Exception ex) {
                System.out.println("Exception occured");
            }
        }
    }

    @Transactional(rollbackFor = {RuntimeException.class})
    private void getNameString(List<Expense> expenses, int start, int end) throws RuntimeException {
        List<Expense> test = new ArrayList<>();
        
        for (int i = start; i < end; i++) {
            Expense temp = expenses.get(i);
            temp.setItem(temp.getItem() + i);
            test.add(temp);
        }

        expenseRepository.saveAll(test);

        throw new RuntimeException("Timeout");
    }



}
  • This question has been answered numerous times before. SPring aop uses proxies only external method calls will work with aop not internal calls. Basically the `@Transactional` is useless here. – M. Deinum Oct 05 '21 at 08:54
  • Thanks, M.Deinum, Need your help, If I want to roll back the particular update on any error that occurs. Right now batch is also saved if any exception occurs. – Nitin Sharma Oct 05 '21 at 09:11

0 Answers0