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

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.

Related

Model classes vs Model in MVC

Does the model in MVC contain both business logic (algorithms and stuff) and the classes that are mapped to entity tables in databases? Those mapped classes are called model as well, specifically, because they model some data. My confusion is this: Does model contain the business logic? or is it just entities? It turns out that it contains, from Mozilla docs: Model: Manages data and business logic.
I got confused by how Java Spring projects are structured. There are controllers, service (business logic), repository(connection to database, aka DAOs) and model classes (Classes of objects that are received by controller and often mapped to database entities). Let's map this to MVC "components":
View - Not in a spring app;
Controller - Rest controller (or just Controller, depending on how you want to structure your app);
Model - Services, Repositories, Model classes (???).
I am confused here, that we have model in both left and right sides.
Thanks.
Edit: Adding a snippet of code, and the structure of app.
This is how spring application looks usually. What most of people do.
.
├── BasicSpringAppApplication.java
├── controller
│   └── CustomerController.java
├── model
│   └── Customer.java
├── repository
│   └── CustomerRepository.java
└── service
└── CustomerService.java
This is how model/entity looks in a java file:
package com.example.basicspringapp.model;
public class Customer {
private String id;
private String name;
private String surname;
private int age;
//constructors, getters, setters
}
Look what I called (and what they call usually) a model, only a specific thing, an entity. But in MVC it's more than that! Model includes not only entities, but services and repositories as well, anything which is not a view and a controller.
Why MVC pattern is messed up in usual spring applications? It seems messed up for me, at least. Why people doesn't call those classes an entity or something like that? Since the model is more than that, for MVC.
The model in MVC-based applications:
In an MVC-based application, the domain model (or, short, the model) mirrors a certain business. It is programmed as a layer - the model layer, or the business layer - and is composed of multiple objects of various types:
Data mappers: transfer data between entities and the chosen persistence space (database, session, remote repository accessible through SOAP, etc).
Repositories: transfer data between entities and the chosen persistence space, too, though by using data mappers from the data mapers layer. They build a layer additional to the data mappers layer, in order to hide the type of persistence space from their users. Each repository object is coded as a collection of entities of a certain type, accessible in a collection-like manner. So, for example, a collection of Book entities could be named BookCollection, or Library, or BooksRepository and would contain methods used to handle a collection of objects of type Book, like: "find/get/remove/update/store/exists/count/etc the book(s) in the book collection".
Entities, or domain objects: to hold the data and the behavior requested by the specific business. These components contain the business logic which is independent of the application in which they are used. In other words, they can be reused by multiple applications.
Value objects.
Services, as part of the service layer. These objects contain business logic as well, but, in comparison to entities, their business rules are dependent of the application in which they are used. Because of this fact, it is debatable if the service classes should be defined as part of the domain model, or of the delivery mechanism (see the first two resources below).
So, in MVC-based applications:
the model is not a class, but a layer of objects with different responsibilities;
the model contains business logic in both entities and services;
the domain objects contain both data and behavior.
By themselves, the entities are NOT mapped in any way to any persistence system (like a database). Their properties and methods mirror the specific business, by using a business-specific vocabulary, therefore beeing completely independent of the structure of the chosen persistence system. It is the responsibility of the data mappers - and theirs only! - to know about and map between the properties of the domain objects and the structure of the database records, for example.
In the first two resources below, at least, you'll discover that, in MVC-based applications, the persistence system (database, etc) does NOT determine the structure of the application. The persistence system is "just a detail".
Notes:
Injecting other components of the model layer beside services into controllers results in wrongly having business logic in them. The sole purpose of the controllers should be to delegate the processing of the user request to the service layer.
The advantages and disadvantages of the object-relational mapping systems (ORMs) are debatable.
Resources:
Keynote: Architecture the Lost Years by Robert C. Martin
Sandro Mancuso : Crafted Design
How should a model be structured in MVC?
Unbreakable Domain Models with slides
DDD Building Blocks: Value Object
Validating Value Objects
A definition of the Ubiquitous Language
The tutorials of Alejandro Gervasio, with PHP code: Building a Domain Model – An Introduction to Persistence Agnosticism, Building a Domain Model – Integrating Data Mappers, Handling Collections of Aggregate Roots – the Repository Pattern, An Introduction to Services
Challenges of object–relational mapping, Object–relational impedance mismatch

How naming objects returned by Controllers, Service and Repositories?

In Spring MVC we have 3 main categories of objects: Controllers, Services and Repositories.
I'm not able to "categorize" the objects returned by these three categories.
For example, the repositories return Entitys, but how could I name the objects returned by services and controllers?
In a real project I'm developing I have a repository returns an extraction from a table, so I get Entities objects. Into the service, where the logic is, I need only to return some fields, so I need to map the entities to another object-model. Later into the controller maybe I will need some layer specific presentation, for example between "standard-computer" and mobile, so I need another type of object to map the result of the service.
Each layer has its postfix in the name of the class to keep the codebase clean and readable. In most of the projects I have worked on, the naming convention is:
Controller layer
The POJO exposed outside of the application, for example, thought a REST API is DTO (Data Transfer Object), so it is usually under the dto package, and the name is like UserDto
Service layer
The POJO that handles the application's business logic is called domain object, so it is usually under the domain package, and the name is like User without any postfix in the name.
Repository layer
The POJO that holds the data in the persistence layer is called entity, so it is usually under the jpa package, and the name is like UserJpa

Spring Controllers logic

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.

Spring MVC 3 - Binding an 'immutable' object to a form

I have several thoroughly unit-tested and finely crafted rich DDD model classes, with final immutable invariants and integrity checks. Object's instantiation happens through adequate constructors, static factory methods and even via Builders.
Now, I have to provide a Spring MVC form to create new instances of some classes.
It seems to me (I'm not an expert) that I have to provide empty constructor and attribute's setters for all form's backing classes I want to bind.
So, what should I do ?
Create anemic objects dedicated to form backing and transfer the informations to my domain model (so much for the DRY principle...) calling the appropriate methods / builder ?
Or is there a mecanisms that I missed that can save my day ? :)
Thank you in advance for your wisdom !
The objects that are used for binding with the presentation layers are normally called view models and they are DTOs purposed toward displaying data mapped from domain objects and then mapping user input back to domain objects. View models typically look very similar to the domain objects they represent however there are some important differences:
Data from the domain objects may be flattened or otherwise transformed to fit the requirements of a given view. Having the mapping be in plain objects is easier to manage than mappings in the presentation framework, such as MVC. It is easier to debug and detect errors.
A given view may require data from multiple domain objects - there may not be a single domain object that fits requirements of a view. A view model can be populated by multiple domain objects.
A view model is normally designed with a specific presentation framework in mind and as such may utilize framework specific attributes for binding and client side validation. As you stated, a typical requirement is for a parameterless constructor, which is fine for a view model. Again, it is much easier to test and manage a view model than some sort of complex mapping mechanism.
View models appear to violate the DRY principle, however after a closer look the responsibility of the view model is different, so with the single responsibility principle in mind it is appropriate to have two classes. Also, take a look at this article discussing the fallacy of reuse often lead by the DRY principle.
Furthermore, view models are indeed anemic, though they may have a constructor accepting a domain object as a parameter and a method for creating and updating a domain object using the values in the view model as input. From experience I find that it is a good practice to create a view model class for every domain entity that is going to be rendered by the presentation layer. It is easier to manage the double class hierarchy of domain objects and view models than it is to manage complex mapping mechanisms.
Note also, there are libraries that attempt to simplify the mapping between view models and domain objects, for example AutoMapper for the .NET Framework.
Yes you will need to create Objects for the form to take all the input, and the update the your model with this objects in one operation.
But I wont call this objects anemic (especially if you do DDD). This objects represent one unit of work. So this are Domain Concepts too!
I solved this by creating a DTO Interface:
public interface DTO<T> {
T getDomainObject();
void loadFromDomainObject(T domainObject);
}
public class PersonDTO implements DTO<Person> {
private String firstName;
private String lastName;
public PersonDTO() {
super();
}
// setters, getters ...
#Override
public Person getDomainObject() {
return new Person(firstName, lastName);
}
#Override
public void loadFromDomainObject(Person person) {
this.firstName = person.getFirstName();
this.lastName = person.getLastName();
}
// validation methods, view formatting methods, etc
}
This also stops view validation and formatting stuff from leaking into the domain model. I really dislike having Spring specific (or other framework specific) annotations (#Value, etc) and javax.validation annotations in my domain objects.

What is the difference between an MVC Model object, a domain object and a DTO

What is the difference between a MVC Model object, a domain object and a DTO?
My understanding is:
MVC Model object:
Models the data to be displayed by a corresponding view. It may not map directly to a domain object, i.e. may include data from one or more domain objects.
Client side
May contain business logic. Eg. validations, calculated properties, etc
No persistence related methods
Domain object:
An object that models real-world object in the problem domain like Reservation, Customer, Order, etc. Used to persist data.
Server side
No business logic
DTO (Data Transfer Object):
An object used to transfer data between layers when the layers are in separate processes, e.g. from a DB to a client app. Allows a single transaction across the wire rather than multiple calls when fetching data corresponding to multiple domain objects. A DTO contains just data and accessor methods and there is no logic present. The data is for a particular DB transaction, so it may or may not directly map to a domain object as it may include data from one or more domain objects.
Used on both server and client sides as it is passed between layers
No business logic
No persistence related methods
So, the questions:
Is above understanding correct? Am I missing some key points?
Are there any reasons not to use Domain objects as the MVC Model assuming that the Model objects do not require extra business logic?
Are there any reasons not to use DTOs as the MVC Model assuming that the Model objects do not require extra business logic?
Domain and model objects are essentially the same, and may contain business logic. Depending on implementation, domain and DTO objects may be equivalent if you remove business logic from the model into a service class.
Often a key variant of the DTO is the View Model, which is used purely to transfer data between the domain model and the view, although often a View Model may contain logic, although this should be purely UI logic.
The Domain and DTO can also be your "model" objects - you can have a view to render the details of the "Customer" domain object.
A domain object can have business logic to enforce the properties of the domain entity. validation is one such case. The domain object by itself does not contain persistence related methods, but it can have meta-data (like annotations) to support persistence
the POJO programming model makes it possible to use the same object as your domain, DTO and model objects - essentially, you will not be implemented any extraneous interfaces that will only apply to one layer but does not apply to others.
A DTO = is an object that carries data between processes.
But the most interesting part is that, it does not have any behavior except for storage and retrieval of its own data!!!
Sticking with the MVC methodology...
Domain = subject of your entire application.
Model = contains the (programming languages objects : EX: C# objects) to make up the universe of your application.
They can obvioussly have behaviour and properties(see difference with DTO).
Often an application (a light one) can have one model - case in which your model is exactly your domain.
Another model can be, a totaly different object type, that is processing another one. Both of them, in this case are part of your domain, and are named "domain models - objects".
Hopefully this answer is exhaustive and makes it all clear for you !
My understing (in a big short) is as follows:
(MVC) Model object:
represent some things in a some usage context eg. PersonEditModel, PersonViewModel or just PersonModel
has no business logic
can be subject of some valdation logic etc.
used to provide data from one application layer to another eg. MVC Controller <-> MVC View
Domain object:
represents some business object (real world object in the problem domain)
has business logic
do not allow invalid object state, has methods to properly change object's state
used to encapsulate business logic related to it
have not to be used to persist data (or even should not)
DTO (Data Transfer Object):
similar to Model object but should have flat structure
only simple type properties/fields (strings, numbers, datetimes, booleans)
used to transfer data cross application boundaries eg. between web server and web browser
Any definition for most of the objects is various based on place of using of objects:
Model: is a general definition for using object in client or server.
Model View : is a object using in client most of the time.
Domain Object : is a object using in server and transfering data to the database.
Data Transfer Object(DTO) : is a object that transfer data from one object to another object, specially in getting data in API Call(for example: in api GET Method call for getting data you must not to give database models to client, for this purpose you use dto).
Notice: the definitions are true most of the time but in some situations arent't practical.
MVC and DDD can be used together. What we call "Models" both in DDD and MVC are virtually the same: abstractions. Using pseudo-code we can illustrate a few examples.
Model View Controller (MVC)
The Model View Controller ARCHITECTURE separates the software into three parts:
The Model Layer
The Model layer from the MVC Architecture is where the logic resides. In this layer we have our models and business logic.
class Car {
String color;
String year;
Cat(color, year) {
this.color = color;
this.year = year;
}
//getters & setters
}
A simple Car abstraction.
class CarService {
save(car) {
if(car.getColor() != null && car.getYear() != null) {
methodToSave(car);
} else {
throwsException();
}
}
find(car) {
return methodToFind(car);
}
update(car) {
assertThatExists(car);
methodToSave(car);
}
delete(car) {
assertThatExists(car);
methodToDelete(car);
}
}
A simple CRUD for Car using a Service
The View Layer
The View layer is where the user interface resides. Here's where the user can interact with the system, which will then trigger the Controllers on actions performed, which will then inform the Model layer and request data. The View Layer can reside either in the client-side of the application or the server-side of the application (ie: JSF (Java Server Faces) as Server-Side, ReactJS as Client-Side). By any means, even if the View layer resides on the client side, the client will need to request the server-side for sending requests. This may be done by HTTP requests for a Web-Based Application.
<theCarPage>
<theCar>
getTheCarOnLoad();
</theCar>
</theCarPage>
A pseudo-page for the Car.
The Controller Layer
The Controller layer basically receives input from the View and then convert and send the data to the Model Layer and vice-versa.
class CarController {
#OnLoadingTheCarPage
getTheCarOnLoad() {
return theCar();
}
}
The method to load the Car.
Domain Driven Design (DDD)
Domain Driven Design is a concept:
DDD lays it's foundations in the concept that classes, class variables and class methods must match it's core business domain.
Domain Driven Design Resides into the "M"
In this case, when MVC is applied, the Domain Driven Design resides into the Model Layer of the MVC Architecture. As explained before, the Model Layer is where the Business Logic of the application resides.
Either if you have entities or not, they still are Models. A Model is just an abstraction of something in the real world. A cat can be a Model if abstracted:
class Cat {
String color;
String age;
Cat(color, age) {
this.color = color;
this.age = age;
}
//getters & setters
}
Simple Cat abstraction. It is a Model of Cat.
DDD Entities
In Domain Driven Design we have Entities, that are also classified as Models. The difference between them is that Entities are identifiable. If you have a class that is identifiable and can be persisted, then it's an Entity. An Entity still, is a Model.
#AnEntity
#ThisCanBePersisted
class Cat {
#ThisIsAnId
#ThisValueIncrementsAutomatically
#PersistentProperty
Long id;
#PersistentProperty
String color;
#PersistentProperty
String age;
Cat(color, age) {
this.color = color;
this.age = age;
}
//getters & setters
}
A simple Entity. An Entity is a Model.
Data Transfer Objects (DTO)
Data Transfer Objects have no logic inside them and the only use to them is to be containers for transferring data from one endpoint to another. Usually Enterprise Entities are not Serializable by nature, so we need a way to send only the data that we need to be sent to a client.
Since a Model could have sensible data or simply data we don't want to share in a request for a fetch, for instance, then considering our Cat Model, we could create a DTO that does not share the Cat's ID:
class CatDTO {
String color;
String age;
//getters & setters
}
A Data Transfer Object for Cat. We only need it's properties and something to get and set the properties. We don't want to share it's ID.
So if we, for instance, had to request a list of all cats from our client using REST, then we would request the endpoint that responds with our CatDTO instead of our Cat Entity:
[
Cat {
"color": "yellow",
"age": "1"
},
Cat {
"color": "black",
"age": "4"
}
]
And that would be all the data that our client could see.
1) No, It is a definition of ViewModel. MVC Model Object and Domain Object both are same.
2) Domain Models (Objects) are always present, business logic is optional
3) If there is no business logic in Domain Object then automatically it becomes DTO.

Resources