Transactional annotation not working as expected

Viewed 35

I have an issue with rollbacking in @Transactional. When rollback is called, rollback itself is working, but another method after is executed.

@Transactional(rollbackFor = { Exception.class })
@Service
public class Service {

    public void method1() {
        stuffToGetListOfObjects();
        deleteAllAndSaveAll(listOfObejcts);
        Util.staticMethod();
    }

    private deleteAllAndSaveAll(List list) {
        repository.deleteAll();
        repository.saveAll(list);
    }
}
@SpringBootApplication
public class Application implements ApplicationRunner {

    private final Service service;

    @Autowired
    public Application(Service service) {
        this.service = service;
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        service.method1();
    }
}

When something goes wrong during the insertion in repository.saveAll(list), no data is actually deleted which is fine and expected. The issue is program is going on the Util.staticMethod() method is executed "after" rollback. I know that static methods cannot be @Transactional and private methods are ignored, but that doesn't seem the issue here. According to the log, everything in method1() is executed first and after that, the inserting is happening. I guess I need to pick out the Util.staticMethod() calling from transaction somehow.

1 Answers

That's why you should separate the repository actions from the service functions. Repository actions are rollbacked. If you separate them the repository level will throw an error and rollback itself. And before the static method, you can check whether the transaction is finished or not by @transactionaleventlistener.

Related