Conversion of DTO to entity and vice-versa

前端 未结 6 1180

I am using Spring MVC architecture with JPA in my web application. Where to convert data transfer object (DTO) to JPA entity and vice-versa, manua

6条回答
  •  渐次进展
    2020-12-25 12:23

    This is an old question with accepted answer but though to update it with easy way of doing it using model-mapper API.

    
        org.modelmapper
        modelmapper
        0.7.4
    
    

    Using this API, you avoid manual setter & getters as explained in accepted answer.

    In my opinion, both conversions should happen at controller with the help of private utility methods and using Java8 stream's map ( if a Collection of DTOs is exchanged ) like illustrated in this article.

    It should happen at controller because DTOs are meant to be exclusive transfer objects. I don't take my DTOs further way down.

    You code your service & data access layers on entities and convert DTOs to entities before calling service methods & convert entities to DTOs before returning response from controller.

    I prefer this approach because entities rarely change and data can be added / removed from DTOs as desired.

    Detailed model mapper configuration and rules are described here

提交回复
热议问题