'Java deep copy bean different types
I am using SpringBoot with Java 1.8.
I have two objects that I would like to copy one to the other. I thought I could use BeanUtils.copyProprties and copy each level of every bean, but because going forward I am going to have to copy many objects, I want to create one generic method to do a deep copy of many objects.
Also, the reason why BeanUtils.copyProprties won't work for me, is because I am copying beans with the same name but different object types.
For example, I want to copy a DTO to an Entity.
DTO
public class QuoteRequestDTO {
protected TravelRequirementDTO travel;
...
and
public class TravelRequirementDTO {
protected String value;
...
Entity
public class QuoteRequest {
protected TravelRequirement travel;
...
and
public class TravelRequirement {
protected String value;
...
Copy Utility
I have tried the following:
import com.fasterxml.jackson.databind.ObjectMapper;
public class CopyUtils {
public static <T>T deepCopy(Object sourceObject, T targetObject) {
ObjectMapper mapper = new ObjectMapper();
T targetBean = (T) mapper.convertValue(sourceObject, targetObject.getClass());
return targetBean;
}
}
Usage:
public void getQuote(QuoteRequestDTO quoteRequestDTO) {
QuoteRequest quoteRequest = new QuoteRequest();
quoteRequest = CopyUtils.deepCopy(quoteRequestDTO, quoteRequest);
Error
It gets the following error:
No serializer found for class com.clubtravel.restosgi.dto.transit.TimeFrameDTO and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.clubtravel.restosgi.dto.transit.availability.QuoteRequestDTO["travel"]
Question
Is there a way I can write a generic utility method to deep copy objects that have member variables with the same names (but different object types)?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
