javamodelmappertypemaps

How can I solve the incompatible types (not convertible) while using the moddelmapper with a typemap


I am trying to map my entity to my DTO. For my knowlegde I'm trying different approaches. I succesfully used a map with implicit mapping, also an explicit map while using a PropertyMap with the configure method.

Now I'm trying to map explicit with the TypeMap. This last one I can't get to work.

Together with the getting started from Modelmapper, I used the answer in this thread as an example, How to use Explicit Map with Java 8 and ModelMapper?

static ResponseB convertBEntityToDtoExplicitTypeMap(ModelB modelB){
    ModelMapper modelMapper = new ModelMapper();
    TypeMap<ModelB, ResponseB> typeMap = modelMapper.createTypeMap(ModelB.class, ResponseB.class);

    typeMap.addMappings(mapping -> {
        mapping.map(modelB.getId(), ResponseB::setId);
        mapping.map(modelB.getBankaccountName(), ResponseB::setB);
        mapping.map(modelB.isActive(), ResponseB::setActive);
    });

    return modelMapper.map(modelB, ResponseB.class);
}

The above block is my code example that doesn't work.

How could I make this example work with the TypeMap?


Solution

  • And by keep trying I figured it out myself.

    I had to use the class instead of the object in the mapping.map

    static ResponseB convertBEntityToDtoExplicitTypeMap(ModelB modelB){
        ModelMapper modelMapper = new ModelMapper();
        TypeMap<ModelB, ResponseB> typeMap = modelMapper.createTypeMap(ModelB.class, ResponseB.class);
    
        typeMap.addMappings(mapping -> {
            mapping.map(ModelB::getId, ResponseB::setId);
            mapping.map(ModelB::getBankaccountName, ResponseB::setB);
            mapping.map(ModelB::isActive, ResponseB::setActive);
        });
    
        return modelMapper.map(modelB, ResponseB.class);
    }