Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of DTO to entity and vice-versa

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)?

like image 282
xyz Avatar asked Feb 24 '15 18:02

xyz


People also ask

Is DTO same as entity?

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.

Can DTO extend entity?

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.


2 Answers

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

like image 196
Sabir Khan Avatar answered Oct 08 '22 16:10

Sabir Khan


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!

like image 33
WesternGun Avatar answered Oct 08 '22 18:10

WesternGun