Roberto Correia
Roberto Correia

Reputation: 1726

Spring Design Patterns recomendation for a rest application

First time developing a REST application, and no previous knowledge on Spring Framework. Almost all Web applications I have developed are in PHP (Laravel), C# (ASP.NET and MVC) or Python (Django).

When the subject is design patterns, I get really confused.

Using the guides available on https://spring.io/guides (https://spring.io/guides/tutorials/bookmarks/), I see that a design pattern was to use:

Entity, Repository, Service and Controller (RestController), like:

When user request a /user/{id} (just a example), the Controller ask for the Service to return the user, so, the Service ask to Repository, that return with a Entity, and so, the Service pass this Entity to Controller (at least in this example);

request = Controller -> Service -> Repository -> Entity
response = Repository return Entity -> Service -> Controller

First thing:

is this correct? I known this works, but it's a common practice (or at least a "best practices")?

For me, don't appear to be correct pass a Entity (if this entity is a exact representation of a object in the database) to my controller.

Suppose that my Entity has a password property. I'm passing the password to my controller. Sure I can "hide" the password on service before return to the controller, but still, the controller will be receiving a entity with a password property.

Now, on reverse way. Suppose that I want to create a new user (Entity), and in my database, I have a property with expirationDate which is calculated automatically, based on the registration date. My Entity representation must have a expirationDate property, but in post, I don't need (and I should not) pass any value to this property.

What's the "best practices" in this cases? In C# / MVC / ASP.NET, normally I used a new Entity for theses cases (aka ViewModel).

Looking at http://www.robertomarchetto.com/java_rest_api_best_practices_spring_boot, I see another design pattern, and appear that exist a Entity (or DTO) for every type of response (like UserResponseDto and UserRegistrationDto in my example - DAO is the same than Repository?).

So, in my example is correct to use this pattern?

request -> Controller -> Service -> Repository -> Entity (DB representation)
response -> Repository return a Entity -> Service convert Entity to a DTO -> Controller

Upvotes: 3

Views: 6142

Answers (1)

René Link
René Link

Reputation: 51353

For the service

  • return type: introduce a transfer object that holds only the data that the controller needs.

  • parameter type: introduce a transfer object that holds only the data that the service needs.

I summerized my thoughts about service layer designs in my blogs that you might be interested in:

Upvotes: 2

Related Questions