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, manually (that is, without using any framework)?
Difference between DTO & Entity: Entity is class mapped to table. Dto is class mapped to "view" layer mostly. What needed to store is entity & which needed to 'show' on web page is DTO.
Usually, a DTO will be a subset of the entity data or also contain data from other associations in sub-DTOs or directly embedded in that DTO. If the DTO extends the entity, a user of a DTO object will have the possibility to invoke a getter to access all that state.
This is an old question with accepted answer but though to update it with easy way of doing it using model-mapper API.
<dependency> <groupId>org.modelmapper</groupId> <artifactId>modelmapper</artifactId> <version>0.7.4</version> </dependency>
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With