Transaction control application rest in spring

1

I was studying a bit about the @Transactional annotation (Spring version), and I had a question. According to a publication made in DevMedia , the way more correct "to use is noting in our business method, because there can have several actions in the bank, not one in specific. So I thought to myself, if in my RestFull application, it would not be more feasible to jot down the endpoint (which only calls a method) to make a transaction of everything from that point forward. Example:

    @PostMapping
    @Transactional(propagation = Propagation.REQUIRED)
public Response< ? > criarNovaViagem(@RequestBody ViagemRequest novaViagem) throws ViagemServiceApplicationException {
        return new Response<>(true, this.viagemService.criarViagem(novaViagem), null);
}

This method " criarNovaViagem() " does N operations in N different tables. Is it wrong or "pig" I annotate my endpoint with @Transacional ?

    
asked by anonymous 25.05.2018 / 19:09

2 answers

1

It's a matter of responsibility, which in turn reflects on flexibility and avoids various other issues.

The Controller should not know anything about the database, much less open a transaction with the database. Its responsibility is to take the information of the HTTP request and to pass to the other classes (Services), controlling the call of classes and obtaining at the end the result to pass to the user of the application.

What each Service does is its sole responsibility. Some can save / query something in the database, others can do operations in external environments (integrations), etc. That is, it makes no sense to open a transaction for everyone below Controller and he has no idea what Services will need.

What are the consequences when you disrespect this?:

  • If there is any integration with external environment and this integration presents some problem with timeout , the whole transaction will wait for this integration that has no relationship with database.
  • If you need to persist in the database before closing this Controller transaction, you will not be able to. If you have any Service that does this or would like it done, it will be impaired.
25.05.2018 / 22:12
0

It can be bad from an architectural point of view and a separation of responsibilities.

Your controller, by definition, should not know the details of processes regarding database persistence or serve as a bridge to traffic for this information.

This role lies with the services layer (yes, the bridge between persistence and data entry) and that is why it is traditionally advised to put this annotation in it.

    
25.05.2018 / 20:09