Spring Controllers logic - spring

I have a question connected to Spring REST and controllers.
I create football application. My application has clubs and players in database. I have an API RestController for clubs and API RestController for Players.
Is it a good way to add players to club in club's controller or I should do this in player's controller or it doesn't matter? Which is a better way?
For example, in my club's controller I have some CRUD methods for clubs and I created methods to get/add players from/to club by club id, get/add player by id for club, etc. Is it ok or should it be in player's controller?
In general, how to think about this controllers logic - how to separate connected part of application?

You should not access database directly from controllers. Controllers should be your presentation layer, and those crud methods should be tied to repository which is used by service.
#Controller - accept HTTP request and activate service
#Service - for your business logic
#Repository - data access logic
So, you should use #Controller to pass data to #Service which offers higher level abstraction over your #Respository CRUD operations.
Added spring reference for more detailed explanation:
#Repository
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Repository.html
#Service
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Service.html
Regarding the player - club relationship:
many to one and one to many are in fact same relationship from a different viewpoint, both approaches are technically correct. Decide for whichever makes more semantic sense to you.

Related

Why do we need to call Service layer using Interface instead of direct service class from controller in spring

When spring was introduced its advice to use an interface between different layers like Controller,Service,DAO instead of directly calling them using actual class reference.
In new age of Spring 5.x and Spring Boot 2.x do we need to still use interface between Controller and Service class. In my case I am developing a REST application with single GET method which call DB and do some business logic. So In my service I have only one method in this case still I do need to use ServiceInterface to call my actual ServiceImpl? what is best practice and is there any specific advantage of using ServiceInterface in this scenario?
Below is Sample code without ServiceInterface
public class MyTestController{
private MyTestServiceImpl myTestServiceImpl;
public MyTestController(MyTestServiceImpl myTestServiceImpl){
this.myTestServiceImpl = myTestServiceImpl;
}
#GetMapping("/test")
public String getTestString(){
myTestServiceImpl.getTestString();
}
}
#Service
public class MyTestServiceImpl(){
private MyTestRepository myTestRepository;
//constructor
//Service method impl
}
In very small applications, it doesn't really matter, because it is still very easy to keep track of all the classes and what classes do what. In a large scale enterprise application it can quickly become a cluttered mess. For example, if you have a rest endpoint/controller that has 100 methods, and it in turn calls 50 methods in your DAO. If you at some point decide to change the DAO methods, you will now have to change all 100 methods in the controller/endpoint. Whereas if you have a service layer in between to bridge the DAO and rest controller you only have to change the service methods.
Another point as #p.streef has mentioned is the seperation of classes and their functions. You can have a modular application wherein the service layer handles all the business logic and rules, the DAO is only responsible for database operations and the controller's only job is to send and receive data. The S in S.O.L.I.D stands for Single responsibility principle, so instead of the service layer is supposed to handle only receiving and transmitting data, and not business logic.
However, if you are building a very very small application then it shouldn't matter.

How to assemble (and re-use) embedded objects in resource classes?

I have a project where domain classes and REST resources are split up.
My domain model contains classes like Hotel, Customer, Country, Continent. Both the Hotel and Customer model have a reference to the Country and Country itself has a reference to Continent.
In my REST model I have a HotelResource and a CustomerResource (both extending Spring HATEOAS's ResourceSupport).
And to transform from the domain model to REST model I also have assemblers extending ResourceAssemblerSupport.
In my REST model I have entities like Country and Continent but they are not identifiable by a link, there is e.g. no endpoint to retrieve only a country or list all countries.
So a CountryResource extending ResourceSupport seems not right as ResourceSupport implements Identifiable.
Country and Resource are some kind of embedded classes for resources.
How should I treat them to re-use the json rendering of them? I mean these embedded Country and Continent are included in multiple Resource classes and I only want to code the transformation once...
Before using Spring HATEOAS I had my own Resource and ResourceAssembler classes which I used for both HotelResource and CountryResource but it could be argued if that is right as CountryResource is not really a resource.
I think if your REST model grows this kind of question will raise - e.g.. to re-use logic for embedded objects - and I wonder what the best practices are from Spring HATEOAS library perspective.

Identifying Spring MVC architecture pattern

I'm working through a spring mvc video series and loving it!
https://www.youtube.com/channel/UCcawgWKCyddtpu9PP_Fz-tA/videos
I'd like to learn more about the specifics of the exact architecture being used and am having trouble identifying the proper name - so that I can read further.
For example, I understand that the presentation layer is MVC, but not really sure how you would more specifically describe the pattern to account for the use of service and resource objects - as opposed to choosing to use service, DAO and Domain objects.
Any clues to help me better focus my search on understanding the layout below?
application
core
models/entities
services
rest
controllers
resources
resource_assemblers
Edit:
Nathan Hughes comment clarified my confusion with the nomenclature and SirKometa connected the architectural dots that I was not grasping. Thanks guys.
As far as I can tell the layout you have mentioned represents the application which communicates with the world through REST services.
core package represents all the classes (domain, services, repositories) which are not related to view.
model package - Assuming you are aiming for the typical application you do have a model/domain/entity package which represents your data For example: https://github.com/chrishenkel/spring-angularjs-tutorial-10/blob/master/src/main/java/tutorial/core/models/entities/Account.java.
repository package - Since you are using Spring you will most likely use also since spring-data or even spring-data-jpa with Hibernate as your ORM Library. It will most likely lead you to use Repository interfaces (author of videos you watch for some reason decided not to use it though). Anyway it will be your layer to access database, for example: https://github.com/chrishenkel/spring-angularjs-tutorial-10/blob/master/src/main/java/tutorial/core/repositories/jpa/JpaAccountRepo.java
service package will be your package to manipulate data. It's not the best example but this layer doesn't access your database directly, it will use Repositories to do it, but it might also do other things - it will be your API to manipulate data in you application. Let's say you want to have a fancy calculation on your wallet before you save it to DB, or like here https://github.com/chrishenkel/spring-angularjs-tutorial-10/blob/master/src/main/java/tutorial/core/services/impl/AccountServiceImpl.java you want to make sure that the Blog you try to create doesn't exist yet.
controllers package contain all classes which will be used by DispacherServlet to take care of the requests. You will read "input" from the request, process it (use your Services here) and send your responses.
resource_assemblers package in this case is framework specific (Hateoas). As far as I can tell it's just a DTO for your json responses (for example you might want to store password in your Account but exposing it through json won't be a good idea, and it would happen if you didn't use DTO).
Please let me know if that is the answer you were looking for.
This question may be of interest to you as well as this explanation.
You are mostly talking about the same things in each case, Spring just uses annotations so that when it scans them it knows what type of object you are creating or instantiating.
Basically everything request flows through the controller annotated with #Controller. Each method process the request and (if needed) calls a specific service class to process the business logic. These classes are annotated with #Service. The controller can instantiate these classes by autowiring them in #Autowire or resourcing them #Resource.
#Controller
#RequestMapping("/")
public class MyController {
#Resource private MyServiceLayer myServiceLayer;
#RequestMapping("/retrieveMain")
public String retrieveMain() {
String listOfSomething = myServiceLayer.getListOfSomethings();
return listOfSomething;
}
}
The service classes then perform their business logic and if needed, retrieve data from a repository class annotated with #Repository. The service layer instantiate these classes the same way, either by autowiring them in #Autowire or resourcing them #Resource.
#Service
public class MyServiceLayer implements MyServiceLayerService {
#Resource private MyDaoLayer myDaoLayer;
public String getListOfSomethings() {
List<String> listOfSomething = myDaoLayer.getListOfSomethings();
// Business Logic
return listOfSomething;
}
}
The repository classes make up the DAO, Spring uses the #Repository annotation on them. The entities are the individual class objects that are received by the #Repository layer.
#Repository
public class MyDaoLayer implements MyDaoLayerInterface {
#Resource private JdbcTemplate jdbcTemplate;
public List<String> getListOfSomethings() {
// retrieve list from database, process with row mapper, object mapper, etc.
return listOfSomething;
}
}
#Repository, #Service, and #Controller are specific instances of #Component. All of these layers could be annotated with #Component, it's just better to call it what it actually is.
So to answer your question, they mean the same thing, they are just annotated to let Spring know what type of object it is instantiating and/or how to include another class.
I guess the architectural pattern you are looking for is Representational State Transfer (REST). You can read up on it here:
http://en.wikipedia.org/wiki/Representational_state_transfer
Within REST the data passed around is referred to as resources:
Identification of resources:
Individual resources are identified in requests, for example using URIs in web-based REST systems. The resources themselves are conceptually separate from the representations that are returned to the client. For example, the server may send data from its database as HTML, XML or JSON, none of which are the server's internal representation, and it is the same one resource regardless.

Exposing entities through services and partial responses

What do you think about exposing domain entities through services? I tried it in an application, but I came to the conclusion that exposing domain model to the client is not such a good idea.
Advantages:
Really easy to transport data from-to client
List item
(De)Serialization is really easy: just put jackson in the classpath and it will handle it. No extra logic is needed.
No need to duplicate entities POJOs. At least in early stages, the API resources will be pretty much the same as the domain model.
Disadvantages:
The API's get very tightly coupled to the model and you can't change the model without affecting the API
Partial responses. There are cases where you don't want to return all the fields of the entities, just some of them. How do you accomplish it?
So, let's take the following REST example. The following API declares that GET on the user resource returns the following information.
GET
/users/12
{
"firstName":"John",
"lastName":"Poe"
"address":"my street"
}
Usually, I would create a User entity, a user service to return the user and a REST controller to serve the request like this:
#RequestMapping("/users/{id}")
public #ResponseBody User getUser(#PathVariable Long id) {
return userService.findById(id);
}
Should I avoid returning the User entity?
If yes, should I create another class and handle myself the mapping between this class and the entity?
Is there a pattern for this?
How to accomplish partial expansion? (i.e. return only the firstName and lastName for the user)
P.S: using #JSONFilter and ObjectMapper to accomplish partial responses seems too heavyweight to me because you loose the beauty of spring data

what is Model in MVC pattern

I am creating an application were I am using MVC pattern.For this I am considering my view as jsps,controller as servlets and model as DAO objects.I have a doubt that me considering DAO objects as Model is right or wrong?
Model is not a DAO. It is a layer, which contains all the domain logic, and is composed mostly from two types of elements, with following responsibilities:
business logic
data access (usually implemented as DataMapper)
The idea is that business logic should never be tied to the storage mechanism. When you are creating an invoice, the domain object should not care, if data comes from SQL database, MSWord document, remote REST API or just a mocked up data.
You might find this article interesting and relevant: GUI Architectures.
A model in MVC is where the business logic lives.
Looking at the sun Java EE pattern definitions we see that DAOs encapsulate persistence mechanisms and are used by a Business Object. I don't therefore see DAOs as natuarally having any business logic.
In simple systems, a few database tables, or those where the business logic is implemented in
the database (stored procedures, referential integrity checks, triggers) then the DAO is effectively a facade in front of Business Logic, so they pretty much look like the Model. So in some introductory material you may see the DAO as pretty much the only Java expression of the Model.
When we choose to implement our business logic in Java, it would lie in a layer above the DAO, in for example Session Beans, which use the DAOs, and in my mind it's the Session Bean or equivalent which is the Model.
So ask yourself: where is the business logic? That's where the Model really is.

Resources