Control of Rest application transactions in spring

Asked

Viewed 364 times

1

I was studying a little bit on the note @Transactional (version made by Spring), and I came up with a doubt. According to a published in Devmedia, to "more correct form" to use is to write down in our business method, because there can be several shares in the bank, and not only one in specific. So I thought to myself, if in my Restfull application, it would no longer be feasible to write down the endpoint logo (which only makes the one method call) to make a transaction of everything you have from there on. 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 on N different tables. It’s wrong or "pig" I jot down my endpoint with @Transacional?

2 answers

1


It is a matter of responsibility, which in turn reflects on flexibility and avoids several other problems.

The Controller should know nothing about the database, let alone open a transaction with the database. Your responsibility is to take the information from the HTTP request and pass to the other classes (Services), controlling the class call and getting the result to pass to the application user.

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

What are the consequences when this is disregarded?:

  • If there is any integration with external environment and this integration presents any problem of timeout, the entire transaction will be waiting for this integration that has no database relationship.
  • If you need to persist something in the database before closing this transaction from Controller, you won’t. If you have any Service who does this or would like you to do, he will be harmed.

0

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

Your controller, by definition, should not know the details of database persistence processes or act as a bridge to that information traffic.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.