在具有相同属性名称的不同数据类型上使用 ModelMapper

Using ModelMapper on different data types with same attribute name

我有两个 类 说 Animal & AnimalDto
我想使用 ModelMapper 将实体转换为 DTO,反之亦然。
但是 类 应该对于一些具有相似名称的属性具有不同的数据类型。
我该如何实现?

Animal.java

public class Animal {    
    int category;    
    String color;    
    int age;
}    
 

AnimalDto.java

public class AnimalDto {    
    String category;    
    int color;    
    int age;
}

目前我正在手动转换:

class AnimalTransformer {
    private static Category[] categories = Category.values();    
    private static Color[] colors = Color.values();    

    animalEntityToDto(Animal animal) {
          AnimalDto animalDto = new AnimalDto();    
          animalDto.setAge(animal.getAge());
          animalDto.setCategory(categories[animal.getCategory()].toString());
          animalDto.setColor(Color.valueOf(animal.getColor()).ordinal());
    }

    animalDtoToEntity(AnimalDto animalDto) {
          Animal animal = new Animal();    
          animal.setAge(animalDto.getAge());
          animal.setCategory(Category.valueOf(animalDto.getCategory()).ordinal());
          animal.setColor(colors[animalDto.getColor()].toString());
    }
}

您提供的示例可能不是流利的模型映射器的最佳部分,特别是因为转换 enums 有一些特殊的困难,而使用泛型。

无论如何,Converter 或通常 AbstractConverter 都可以做到这一点。

您没有提供枚举示例,因此我创建了最简单的示例枚举:

enum Color {
    PINK;
}

enum Category {
    MAMMAL;
}

要将 Integer Animal.category 转换为 String AnimalDto.category,转换器可以是这样的:

public class CategoryToStringConverter extends AbstractConverter<Integer, String> {
    @Override
    protected String convert(Integer source) {
        return Category.values()[source].toString();
    }
}

并将 String Animal.color 转换为 Integer AnimalDto.category,转换器可以是这样的:

public class ColorToOrdinalConverter extends AbstractConverter<String, Integer> {
    @Override
    protected Integer convert(String source) {
        return Color.valueOf(source).ordinal();
    }
}

用法如下:

mm.createTypeMap(Animal.class, AnimalDto.class).addMappings(mapper -> {
    mapper.using(new CategoryToStringConverter()).map(Animal::getCategory, 
        AnimalDto::setCategory);
    mapper.using(new ColorToOrdinalConverter()).map(Animal::getColor, 
        AnimalDto::setColor);
});

这是从Animal转换为AnimalDto的部分。反之亦然当然需要自己的映射,我没有在这里展示,因为我认为这一点很清楚。

对于一个 class 你现在做的方式可能更好但是如果你需要在很多地方像这样转换 Category & Color 那么你应该考虑使用转换器可重复使用。