Conversion of DTO to entity and vice-versa

前端 未结 6 1176

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 11:58

    I suggest another approach without extra dependency:

    import org.springframework.beans.BeanUtils
    ...
    BeanUtils.copyProperties(sourceObject, targetObject);
    

    Can be used to convert DTO to entity, or vice-versa, if they have same property types and names.

    If you want to ignore some fields, just add them after the targetObject.

    BeanUtils.copyProperties(sourceObj, targetObj, "propertyToIgnoreA", "propertyToIgnoreB", "propertyToIgnoreC");
    

    Source: http://appsdeveloperblog.com/dto-to-entity-and-entity-to-dto-conversion/

    I think this is the cleanest way. Remember to check the Javadoc for caveats!

提交回复
热议问题