0

I want to know the best practices. Following things are confusing: 1) Should model return an Entity or directly a DTO by using select new ExampleDto(...)? 2) How we should convert Entity to DTO or vise versa? 3) Can we use the DTO for Entity to DTO conversion that implements serializable class to convert object injson etc?

Kindly provide your expert opinion, in whatever direction you want.

MDaniyal
  • 1,097
  • 3
  • 13
  • 29

1 Answers1

1

Many may argue upon what to return in model.In my opinion returning dto is good practice. The reason being-

  1. We should try to avoid exposing entity to view.
  2. Many times view requires only subset of Entity, So it is not good to return complete bunch of data in that case.

You may consider using Dozer for conversion from DTO to Entity and vice versa. http://dozer.sourceforge.net/

Md Zahid Raza
  • 941
  • 1
  • 11
  • 28
  • Thanks. I used dozer in past but it is too complex using mapping in xml. Is there a way of conversion on Java level? – MDaniyal Aug 24 '16 at 12:40
  • 1
    If you have used in past using xml mapping. try revisiting it using annotation. It is quiet easy to use using annotation. For simple fields you have practically nothing do. For complex object mapping, you can use create convertor class by just extending DozerConvertor and implement two methods. – Md Zahid Raza Aug 24 '16 at 12:45
  • Thanks @raza yes I should surely revisit it then :) – MDaniyal Aug 24 '16 at 12:54