Jhipster4: what are the benefits of using DTO - java

Jhipster4 adds Data Transfer Objects (DTO) just what is the benefit of using DTO objects?

Main benefit is to control more precisely which properties you expose from your entities and also to expose entity aggregates rather than single entities.

DTO, stands for Data Transfer Object, is a design pattern conceived to reduce the number of calls when working with remote interfaces.
The advantage of using DTOs, is that they can help hiding implementation details of domain objects (aka. entities). Exposing entities through endpoints can become a security issue if we do not carefully handle what properties can be changed through what operations.
For context, here is an example endpoint using DTOs in Java (Spring Boot):
public class ProductDTO {
private String name;
private Double price;
}
public class Product {
private Long id;
private String name;
private Double price;
}
#PostMapping("/products")
public ResponseEntity<ProductDTO> createProduct(
#RequestBody Product request
) { ... }

Go Through this link about DTO.
Data Transfer Object
An object that carries data between processes in order to reduce the number of method calls.
The main reason for using a Data Transfer Object is to batch up what would be multiple remote calls into a single call, it's worth mentioning that another advantage is to encapsulate the serialization mechanism for transferring data over the wire. By encapsulating the serialization like this, the DTOs keep this logic out of the rest of the code and also provide a clear point to change serialization should you wish.

Related

Architectural approach to consume single DTO from many REST services

In my Spring RESTful Service I have Domain Object Car, all service business logic uses it. These objects are obtained from CarDTO objects which in turn are obtained from several external services using RestTemplate.
The questions are:
Is it rational to create separate DTO for each external service if consuming structure is different and map them do domain object by different converters, or it's better to use general DTO and converter?
If my previous suggestions are wrong - what is the pest practice of consuming domain object from several api with different structure?
Car domain object:
public class Car {
private Company company;
private String model;
private Location location;
private Double fuel;
private Double price;
// getters / setters
}
There is no hard and fast rule that you should create DTOs.
You can directly use your DB object(Car) instead of in-between DTOs.
As per my understanding, if there is everything direct field to field mapped then no need for DTOs.
If we have logic or transformations to perform from Request/Response to convert it to DB objects then DTOs are perfect to use to make code clean. It Decouples persistence models from API models and makes code for maintainable.
For more detail, please go through REST API - DTOs or not?

Practical use of Value Objects in Spring MVC application

In my application written in Hibernate and Spring MVC I've got simple classes representing Customer, his main office Address and list of Locations of rest of his offices. There is a form that allows to add and edit data of Customer, then Spring MVC maps it to DTO, validates, sends down to Service which converts it to (slightly different) Entity and saves.
I thought about using value objects for representing and implicit validation for some objects - i.e. PhoneNumber, Address, but I don't really know how to use them in these frameworks - even if I think I understand the Value Object concept and immutability.
If I will use them in DTOs used in presentation layer then I can't rely on Spring mechanism of mapping fields from form to object - because there are no setters. And I must do the mapping manually in Controller or Service.
Should I use Value Objects in Entity (embed them)? Or maybe this is too simple case to use Value Objects at all?
Your question is not primarily about value objects, but your main concern (if I understand correctly) is how to send data from a web form, validate the data and save the data in entities.
Create a form object such as MyForm with all fields that the user can enter in your screen. The form object serves to transport your data to the server, for example:
class MyForm {
#NotBlank
private String name;
#NotBlank
private String phoneNumber;
#NotBlank
private String address;
// getters and setters
}
On the server side controller validate, convert and store the data:
#Controller
class GuestbookController {
#RequestMapping(value = "/guestbook", method = RequestMethod.GET)
String myget(Model model, MyForm form) {
// put data on model
}
#RequestMapping(value = "/mysubmit", method = RequestMethod.POST)
String mysubmit(#Valid MyForm form, Errors errors, Model model) {
if (errors.hasErrors()) {
return myget(model, form);
}
myrepository.save(new MyEntity(form.getName(), form.getPhoneNumber(), form.getAddress()));
return "redirect:/myview";
}
}
You probably need more details about the address than what fits in a single String. Then, yes, using a value object containing all the address details is fine.
here is my humble response.
DTOs are simple data containers with no logic,
and value objects are the opposite and encapsulate the logic.
Just a funny thing, DTOs were called value objects in the past in Java.
One way to see it (as I read it) is to let value objects encapsulate all the logic for entities, entities that handle only identity.
DTOs allow decoupling the domain model from the UI (or any other ports/adapters).
Should value objects be used outside the domain layer ? I don't know but personally I don't do it. In my setups, they are used by the application layer and inside the domain, but outside the application layer there is only DTOs.
I have DTOs that Spring can handle and data mappers to do the translation (dto to model at the UI/app layers border). The DTOs generally can have setters (event public property according to some people).
Now, if you want to use immutable object mapped by the framework, the solution depends on the technology you are using. When I do webservices with JSON (and Jackson), I map immutable commands object directly with #JsonCreator annotation on constructor but I couple my pojos to jackson. To avoid this, you can also add your customer serializers to the framework to let it convert automatically the data structure around controller method parameters.
Otherwise, you always can do mapping with data mapper or factory methods. (I believe you wrote a post about that...)

DTO objects for each entity

I have inherited an application written in Java that uses JPA to access a database. The application uses an design pattern that I haven't come across before and I would really appricate some guidance on why this pattern is used. Like many applications, we have a front end, middleware, and back end database. The database is accessed via DAOs. Each method on the DAO loads a entity-DTO which is just a POJO with nothing but getters and setters and that entity-DTO is then passed into a entity-proper that has other methods that change the entity state. An example [class names changed to protect the inocent]
enum Gender
{
Male,
Female
}
class PersonDTO
{
private String mFirstName;
private String mLastName;
private Gender mGender;
...
String getFirstName() { return this.mFirstName; }
String setFirstName(String name) { this.mFirstName = name; }
// etc
}
class Person
{
PersonDTO mDTO;
Person(PersonDTO dto)
{
mDTO = dto;
}
String getFirstName() { return mDTO.getFirstName() }
String setFirstName(String name) { mDTO.setFirstName(name); }
// and so on
void marry( Person aNotherPerson )
{
if( this.getGender()==Gender.Female &&
aNotherPerson.getGender()==Gender.Male)
{
this.setLastName( aNotherPerson.getLastName() );
}
aNotherPerson.marry( this );
}
}
This is repeated across 30 or so entity classes, doubled to 60 with the DTOs, and I just cant get my head around why. I understand (bits) about seperation of converns and I also understand (bits) about the difference between an EAO based design to say an active record based design.
But does it really have to go this far? Should there always be at least one "DB" object that contains nothing but getters and setters that map to the DB fields?
Disclaimer: there are varying opinions on this subject and depending on your system's architecture you might not have a choice.
With that said... I've seen this pattern implemented before, not a huge fan of it, in my opinion is duplicates large amounts of code without adding any real value. It seems to be particularly popular in systems with XML APIs like SOAP where it might be difficult to map XML structure directly to your object structure. In your particular case it seems to be even worse because on top of duplicate getFirstName()/getLastName() methods, there is business logic (which belongs in the service layer) coded right into a pojo (which should be a simple data transfer object like the DTO). Why should the pojo know that only people of opposite sex can get married?
To help better understand why, can you explain where these DTOs come from? Is there a front-end submitting data to a controller which then converts it to a DTO, which is then used to populate your entity-proper with data?
It could also be that they are using this just to separate the JPA annotations from the rich domain object.
So I'm guessing that somebody didn't like having JPA annotations and the rich domain object behaviour in one class. Somebody could have also argued that the JPA annotation and the rich domain object should not be in the same layer (because the annotations mixes the concerns) so you would get this kind of separation if you won this argument.
Another place where you'd see this kind of thing happening is when you want to abstract similar annotations away from the rich domain objects (like jaxb annotations in web services for example).
So the intent might be that the DTO serves as sort of the serialization mechanism from code to the database, which is very similar to the intent mentioned here by martin fowler.
This doesn't appear to be a known pattern.
In general
it is common to maintain a separate object to represent the record in the database, referred to as domain object.
the CRUD operations on the object are part of a DAO class and other business operations would be part of a Manager class, but none of these classes store the domain object as a member variable, i.e. neither DAO nor Manager carry state. They are just processing elements working on domain objects passed in as parameters.
a DTO is used for communication between the front-end and back-end to render data from DB or to accept input from end-user
DTOs are transformed to Domain objects by Manager class, where validations and modifications are performed per business rules. Such domain objects are persisted in the DB using DAO class.
I have worked on one project where we have DTOs for the sole purpose of transferring information from front-end controller to some facade layer. Then facade layer is responsible for converting these DTOs to domain objects.
The idea behind this layering is to decouple front-end (view) from domain. Sometimes DTOs can contain multiple domain objects for aggregated view. But domain layer always presents clean, reusable, cacheable(if required) objects.

design of building DTO from domain object

I have a graph of domain objects and i need to build a DTO to send it to the view. How to design it properly? I see 2 options where can I put the DTO building code:
1) Into the DTO constructor. But then the domain object has to present all fields to DTO via getters so it's not a DDD.
public DTO(DomainObject domain) {
/// access internal fields of different domain object.
}
2) Into the domain object. There will be no problem with accessing fields but the domain object will grow very fast when new view are added.
public DTO1 createDTO1() {
...
}
public DTO2 createDTO1() {
...
}
// and so on...
How should I build DTOs properly?
I think there is a bigger issue at play here. You should not be querying your domain. Your domain should be focused on behaviour and, as such, will quite possibly not contain the data in a format suitable for a view, especially for display purposes.
If you are sending back your entire, say, Customer object to Edit then you are performing entity-based interactions that are very much data focused. You may want to try and place more attention on task-based interactions.
So to get data to your view I'd suggest a simple query layer. Quite often you will need some denormalized data to improve query performance and that will not be present in your domain anyway. If you do need DTOs then map them directly from your data source. If you can get away with a more generic data container structure then that is first prize.
Variants:
Constructor with simple types in DTO: public DTO(Long id, String title, int year, double price)
Separate class - converter with methods like: DTO1 createDTO1(DomainObject domain)
Framework for copy properties from one object to other, like Dozer: http://dozer.sourceforge.net/
1) ... the domain object has to present all fields to DTO via getters ...
2) ... the domain object will grow very fast ...
As you can see, the problem is that both alternatives are coupling your model with your DTOs, so you need to decouple them: introduce a layer between them in charge of performing the mapping/translation.
You may find this SO question useful.
domain object has to present all fields to DTO via getters so it's not
a DDD
Just because a domain object has getters doesn't make it anemic or anti-DDD. You can have getters and behavior.
Besides, since you want to publish to the View a DTO containing particular data, I can't see how this data can remain private inside the domain object. You have to expose it somehow.
Solution 2) breaks separation of concerns and layering (it's not a domain object's business to create a DTO) so I'd stick with 1) or one of #pasha701's alternatives.

Serializing a part of object graph

I have a problem regarding Java custom serialization. I have a graph of objects and want to configure where to stop when I serialize a root object from client to server.
Let's make it a bit concrete, clear by giving a sample scenario. I have Classes of type
Company
Employee (abstract)
Manager extends Employee
Secretary extends Employee
Analyst extends Employee
Project
Here are the relations:
Company(1)---(n)Employee
Manager(1)---(n)Project
Analyst(1)---(n)Project
Imagine, I'm on the client side and I want to create a new company, assign it 10 employees (new or some existing) and send this new company to the server. What I expect in this scenario is to serialize the company and all bounding employees to the server side, because I'll save the relations on the database. So far no problem, since the default Java serialization mechanism serializes the whole object graph, excluding the field which are static or transient.
My goal is about the following scenario. Imagine, I loaded a company and its 1000 employees from the server to the client side. Now I only want to rename the company's name (or some other field, that directly belongs to the company) and update this record. This time, I want to send only the company object to the server side and not the whole list of employees (I just update the name, the employees are in this use case irrelevant). My aim also includes the configurability of saying, transfer the company AND the employees but not the Project-Relations, you must stop there.
Do you know any possibility of achieving this in a generic way, without implementing the writeObject, readObject for every single Entity-Object? What would be your suggestions?
I would really appreciate your answers. I'm open to any ideas and am ready to answer your questions in case something is not clear.
You can make another class (a Data-Transfer-Object) where you have only the fields you want to transfer.
A way of custom serialization is implementing Externalizable
I would say the short answer to your question is no, such varied logic for serialization can't be easily implemented without writing the serialization yourself. That said an alternative might be to write several serializer/deserializer pairs (XML, JSON, whatever your favorite format, instead of standard yusing the built in serialization). and then to run your objects through those pairs sending some kind of meta-information preamble.
for example following your scenarios above you may have these pairs of (de)serialization mechanisms
(de)serializeCompany(Company c) - for the base company information
(de)serializeEmployee(Employee e) - for an employee's information
(de)serializeEmployee(Company c) - the base information of employees in a company
(de)serializeRelationships(Company c) - for the project relationships
For XML each of these can generate a dom tree, and then you place them all in a root node containing metainformation i.e.
<Company describesEmployees="true" describeRelationships="false">
[Elements from (de)serializeCompany]
[Elements from (de)serializeEmployee(Company c)]
</Company>
One potential "gotcha" with this approach is making sure you do the deserialization in the correct order depending on your model (i.e. make sure you deserialize the company first, then the employees, then the relationships). But this approach should afford you the ability to only write the "actual" serialization once, and then you can build your different transport models based on compositions of these pieces.
You could take an object swizzling approach where you send a "stub" object over the wire to your client.
Pros
The same object graph is logically available client-side without the overhead of serializing / deserializing unnecessary data.
Full / stub implementations can be swapped in as necessary without your client code having to change.
Cons
The overhead in calling getters which result in dynamically loading additional attributes via a call to the server is hidden from the client, which can be problematic if you do not control the client code; e.g. An unwitting user could be making an expensive call many times in a tight loop.
If you decide to cache data locally on the client-side you need to ensure it stays in-sync with the server.
Example
/**
* Lightweight company stub that only serializes the company name.
* The collection of employees is fetched on-demand and cached locally.
* The service responsible for returning employees must be "installed"
* client-side when the object is first deserialized.
*/
public class CompanyStub implements Company, Serializable {
private final String name;
private transient Set<Employee> employees;
private Service service;
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
public String getName() {
return name;
}
public Set<? extends Employee> getEmployees() {
if (employees == null) {
// Employees not loaded so load them now.
this.employees = server.getEmployeesForCompany(name);
}
return employees;
}
}

Categories