0

Background: I'm trying to separate my concerns in the application architecture the best possible way. In a nutshell:

  1. The requests are parsed and go to an Action
  2. Action decides which service(s) to call
  3. Services have the business logic inside
  4. The service returns the data to the action
  5. The action returns a response

Question

When using ORM to retrieve data, does it make sense to retrieve the data directly inside the service using ORM or would you recommend abstracting the data access to another layer?

Is it good practice to directly retrieve data using ORM without an abstraction? If no, why?

Is it good practice to abstract the data access to something like a repository? If no, why?

1

Data access layer abstracts the internals of a data source. When your application is, for instance, storing a change to the price of a product, it shouldn't be concerned about the technical implementation.

It shouldn't have to know that the change is done by performing two update requests to PostgreSQL database while ensuring that at least three replicas acknowledge the update, then the cache items details-of-product<Id>, price-of-product<Id> and top-products-cheaper-than<N> is invalidated in order for the customers to see the new price.

Instead, it should just tell the data access layer to persist the change, and let the data access layer deal with the details. It shouldn't care whether PostgreSQL or MongoDB is used, or whether the information is cached in a Redis cluster or not.

An ORM allows you to access the database without writing SQL queries. The abstraction stops here. It could allow, for instance, to swap Oracle database by Microsoft SQL Server, but it will still leak nearly everything (including the actual schema) to the caller. As soon as your application starts to be more complex, the ORM will happily thrust this complexity to your application.

Therefore, an ORM doesn't replace a data access layer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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