I need transactions in my service to ensure data consistency. I don't know what the best layer is for transactions to be created in. The goal is to have all business logic in a single layer.

First, some example business logic:
There are the entities of person and hobby. Each person can have multiple hobbies. This means there will be the person and hobby tables. When I create a person with its hobbies I must insert them into its respective tables. For example, 1 person with 3 hobbies will be 4 table inserts. If anything fails in this process, everything must be rolled back. Transactions are thus a requirement.

Let me describe the layers of the service:

  • Controllers - this is the entry point to the system. Can be a REST API for example. It handles the input and response, and calls the appropriate methods in business logic layer. Ideally, one method per handler.

  • Business - this is where the business logic lies. It this case, it knows that a person must be created alongside with its hobbies. It will combine the CRUD operations of the lower level to perform business actions, such as person+hobbies creation.

  • Model - this is where all the models reside. This layer knows the has an individual CRUD for each entity, but it does not know about the database directly.

  • Database - this is where the data is persisted and SQL is used. There should be a CRUD for each table.

Both the database and database layers should be pure, in the sense that they don't entities do not interact with each other. So it seems like the best approach is to place transactions in the business layer. Is this the standard approach?

  • 1
    The answer is "yes".
    – Doc Brown
    Jan 9, 2022 at 8:52

1 Answer 1


Yes, this is what transactions are for. Only business logic layer should know if particular operations must be done within a single transaction or not. Controller should not care about transactions and should just use business logic.

Besides, business logic can be potentially called not only from REST controllers, but also from other classes like SOAP Web Services or message/event listeners. If transactions were implemented not in the business logic layer, such logic would have to be duplicated everywhere: In the REST controller, in the SOAP Web Service, in the message/event listener.

That's why: Yes, transactions should be done in the business logic layer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.