Skip to content
Advertisement

How to properly use 3 – layers architerchture in Spring MVC – Java

I come before you with a confusion that, perhaps, you can clarify to me.

I’m learning now how to use 3-layers architecture with Spring MVC (using Repository, Service, Controllers), but I don’t understand the following things and how I should do it:

Service Layer, here, I do not understand, the methods defined in the interface should be the same as those given to us by the JPA or customized on that entity (Product, for example, with methods for getBrand etc) or what methods should we use for each entity, how do we know what to use?

-another thing observed from the found examples is that for a Product entity, in Service, a new class was used, ProductData, having those instances that we are willing to put in view, is it okay to do so or stay with our Entity? If yes, in Service Methods, we should use ProductData instead of Product entity? Example:

public ProductData findById(Integer id){
        ProductEntity product = productRepo.findById(id);
        ProductData data = new ProductData(product.getId(), product.getName(), product.getCeva());
        return data;}

-If we use ProductData in Service, we should use it in controller, too, right?

-What are the purpose of Utility Classes, when and how we should use them, in MVC, for example?

Thanks for patience and for help, i was been searching on google these things, but i didn’t find nothing concludent, just just personal preferences…

Advertisement

Answer

The Repository layer is responsible for handling the communication between your database and the application. Here you can load, save, delete or update your entites. Thats easy.

The Service layer is responsible for the business logic. In simple cases it may seems like a proxy between contoller and repository, but suppose you have to load the Products then calculate price to each, call another web service for pictures from products and put it all together to send back to the client as a response.

So the proper methods here are depend on your requirements.

Most of the time (except for simple examples) you have to serve complex data. So you cannot just return with the simple entity but a composed object.

Another thing is if you return with the entity, it will give back the whole db stucture to the client (id, audit fields, etc…), which is a huge security issue. So the composed object is safer as well as it’s easier to modify the application in the future if requierements change.

Utility classes are just helpers. When you have some common logic and it cannot encapsulated into superclass, you can use it. For example convert dates, check string nullability and emptiness..etc

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement