3

I have rest models that I use to build JSON that I send.

A rest model

@Getter @Setter
@ToString
public class OrderRequestModel {
    private String orderKeyId;
    private String paymentMode;
    private double totalAmount;
    private List<ProductRequestModel> orderProducts;
    private UserDetailsRequestModel seller;
    private Date createdAt;
}

The ProductRequestModel is similar

@Getter @Setter
@ToString
public class ProductRequestModel {
    private String productKeyId;
    private String name;
    private double price;
    private int qty;
    private String imgPath;

    private CategoryRequestModel category;
}

I'm passing the models to a DTO layer which is in relation with database (they include a long Id):

@Getter @Setter
@ToString
public class OrderDto implements Serializable {
    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private static final long serialVersionUID = 1L;

    private Long id;
    private String orderKeyId;
    private String paymentMode;
    private double totalAmount;
    private List<ProductDto> orderProducts;
    private UserDto seller;
    private Date createdAt;
}

And my ProductDto :

@Getter @Setter
@ToString
public class ProductDto implements Serializable {
    // ommit this member and do not generate getter / setter
    @Getter(AccessLevel.NONE)
    @Setter(AccessLevel.NONE)
    private static final long serialVersionUID = 1L;

    private Long id;
    private String productKeyId;
    private String name;
    private double price;
    private int qty;
    private String imgPath;

    private CategoryDto category = new CategoryDto();
}

When i try to map OrderDto with the associated model i do it implicitelly :

OrderDto orderDto = modelMapper.map(orderRequestModel, OrderDto.class);

In theory, orderKeyId from the model should match with its equivalent in the Dto. Unfortunatelly It returns an error :

Converter org.modelmapper.internal.converter.NumberConverter@3e36f4cc failed to convert java.lang.String to java.lang.Long.
Caused by: org.modelmapper.MappingException: ModelMapper mapping errors:

I do need the Id in the DTO because if i want to make an update I do use "id"

davidvera
  • 1,292
  • 2
  • 24
  • 55

1 Answers1

9

This issue is caused because of the Mapping Strategies. We can set the Mapping Strategies to STRICT so that when mapping from source object property to target object's property it only maps only those property which are perfectly matching in property name as well as it's data type. Below is an example.

public ModelMapper modelMapper() {
    ModelMapper modelMapper = new ModelMapper();
    modelMapper.getConfiguration()
        .setMatchingStrategy(MatchingStrategies.STRICT);
}

FYI: http://modelmapper.org/user-manual/configuration/#matching-strategies

Ghost Rider
  • 688
  • 3
  • 17
  • 38