What is the best practice to response a personalized object in my controller?
Example of necessity: I have X entities, and one of my controllers need to return a json object with specific attributes of others entities. Create a package named responses and inside create a class with the personalized fields its a good idea?
public class OrderItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private Integer quantity;
@ManyToOne
@JoinColumn(name= "order_id")
private Order order;
@ManyToOne
@JoinColumn(name= "product_id")
private Product product;
}
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String description;
}
public class ResponseOrderItems {
@JsonIgnore
Integer orderId;
Integer productId;
Integer quantity;
String description;
}
Basically ResponseOrderItems its a class that "compose" attributes from Product and OrderItems and others entities. Should I keep treating it like just a response or like an entity/model?
More details: In service layer, I'm building the ResponseOrderItems with the attributes from the other entities and returning it.
CodePudding user response:
That is definitely the way to go. You should even avoid having your Entities has the response objects on your Controllers. One of the more important reasons is the fact that you might need to adapt your Entities model or your API model but you don't want to modify the other. You can only do that if you have separate models for them. This pattern is named DTO (Data Transfer Object):
DTOs or Data Transfer Objects are objects that carry data between processes in order to reduce the number of methods calls. The pattern was first introduced by Martin Fowler in his book EAA. He explained that the pattern's main purpose is to reduce roundtrips to the server by batching up multiple parameters in a single call. (...) With DTOs, we can build different views from our domain models, allowing us to create other representations of the same domain but optimizing them to the clients' needs without affecting our domain design. Such flexibility is a powerful tool to solve complex problems.
This is similar to what you are trying to do.