Search code examples
spring-mvcspring-boottransactional

How to create transaction to save several objects in the database?


I have a controller in my Spring Boot application. The controller receives json from POST request. Parsing the json I need to create three new objects in the database:

    accountRepository.save(account);
    containerRepository.save(userContainer);
    containerRepository.save(operatorContainer);

Saving this three objects to the database should be in one transaction. For now I'm using @Transactional on controller method. However it seems the bad practice to mark controllers by @Transaction annotation. Should I create service where I would save three objects passed as arguments and mark the service @Transactional? What is the best way to do it? Maybe someone can provide an example?


Solution

  • The best place for this would be in a method in your service layer.

    @Service
    public class MyService {
    
      @Autowired
      AccountRepository accountRepository;
    
      @Autowired
      ContainerRepository containerRepository;
    
      @Transactional
      public void save(Account account, Container userContainer, Container operatorContainer) {
        accountRepository.save(account);
        containerRepository.save(userContainer);
        containerRepository.save(operatorContainer);
      }
    }
    

    Then wire up the service in your controller.