Abdul
Abdul

Reputation: 1208

What is the best way to populate Entity from DTO

I'm creating an order service, new to RestServices world.

I need to read the order model into a OrderDTO and persist in the DB.

For that I have a below method:

@PostMapping(produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<OrderDTO> createOrder(@Valid @RequestBody OrderDTO orderDTO) {
    Order order = new Order(orderDTO);
    Order createdOrder = orderService.createOrder(order);
    OrderDTO createdOrderDTO = new OrderDTO(order);
    ResponseEntity<OrderDTO> responseEntity = new ResponseEntity<OrderDTO>(createdOrderDTO, null, HttpStatus.CREATED);
    return responseEntity;
}

Everything working fine, but I have concerns about the current design:

  1. I'm reading an input into DTO
  2. To Store the object I'm converting into Order object which will be persisted by Hibernate
  3. Again to send the response back I'm converting the actual order object into DTO.

finally I will create 4-5 Objects per a request, if my app got 100 request it may run into memory issue.

How i can read the model data and persist efficiently?

Upvotes: 2

Views: 3138

Answers (3)

Ori Marko
Ori Marko

Reputation: 58892

In general, prefer DTO because of single responsibility principle, every object have its own responsibility and It's also clearer to separate View/Controller from Model objects

You can sometimes reduce OrderDTO, use an object that is both DTD and real Object,

It'll include DTD properties and also other properties that you can add using builder for example, I'm using @JsonIgnoreProperties(ignoreUnknown = true) to set only the DTD properties when object is created from request, e.g.:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class Order 

You can also use JsonGetter/JsonProperty/JsonSetter to control what expected/returned

@JsonGetter and @JsonSetter are old alternatives to @JsonProperty.

Upvotes: 2

Vladimir
Vladimir

Reputation: 710

I prefer a Mapper like Mapstruct:

OrderDtoMapper mapper = new OrderDTOMapper();

Order order = OrderDtoMapper.map(orderDto, Order.class);

and back:

OrderDTO createdOrderDTO = OrderDtoMapper.map(order, OrderDTO.class);

For me the code looks more readable ... and you do not have much to write for, as Mapstruct maps it automatically. Because it looks like you will map quite a lot ;) Perhaps a mapper is worth a try: http://mapstruct.org/

Upvotes: 1

MyTwoCents
MyTwoCents

Reputation: 7622

I don't see any issue with the design.

As Nizet pointed out. Objects created are short lived.

Normally DTO and Entity design is followed to keep the UI and Service Layer separate.

In this way, you have the option to filter out sensitive info from being passed to the world like password, pin.

But if you want you can use Order entity directly in Controller class.

I won't suggest that but it's possible.

Upvotes: 0

Related Questions