我使用 ModelMapper Framework ( http://modelmapper.org/ ) 在 Java 中映射对象。我在映射包含抽象类的具体类(DTO 到实体)时遇到了问题。
示例:任务有一个 AbstractItems 列表。
AbstractItems 是问题和标准。
public class TaskDTO {
   ...
   private List<AbstractItemDTO> items;
}
映射方法:
// task is an TaskDTO object
return getModelMapper().map(task, TaskEntity.class);
ModelMapper 尝试创建 AbstractItem 的新实例,该实例引发异常。有没有办法在运行时映射抽象类?
喜欢 QuestionDTO -> Question, CriteriaDTO -> Criteria
我正在尝试将Java DTO对象映射到现有的JPA实体对象,而不必执行以下操作:
public MyEntity mapToMyEntity(SomeDTO dto, MyEntity entity) {
    entity.setField1(dto.getField1());
    entity.setField2(dto.getField2());
    ...
    entity.setField20(dto.getField20());
    return entity;
}
到目前为止,我一直在使用ModelMapper:MyEntity entity = modelMapper.map(dto, SomeDTO.class);但我正在尝试做的是映射到现有的实体对象,而不是从DTO 创建新的实体对象.我查看了ModelMapper手册,但没有找到如何在不创建新对象的情况下进行映射.我是否为我可能拥有的每个实体对象手动添加每个成员变量?
我无法解决modelMapper错误。您有什么想法吗?
注意:在视图java.sql.Time中没有非参数构造函数,我没有找到比编写转换器更好的方法
org.modelmapper.ConfigurationException: ModelMapper configuration errors:
1) The destination property 
biz.models.CarWash.setSecondShift()/java.util.Date.setTime() matches 
multiple source property hierarchies:
biz.dto.CarWashDTO.getFirstShift()/java.time.LocalTime.getSecond()
biz.dto.CarWashDTO.getSecondShift()/java.time.LocalTime.getSecond()
错误是由此代码造成的
@SpringBootTest
@RunWith(SpringRunner.class)
public class CarWashDTO2CarWash {
@Autowired
protected ModelMapper modelMapper;
@Test
public void testCarWashDTO2CarWash_allFiledShouldBeConverted(){
    CarWashDTO dto = CarWashDTO.builder()
            .name("SomeName")
            .address("SomeAddress")
            .boxCount(2)
            .firstShift(LocalTime.of(9, 0))
            .secondShift(LocalTime.of(20, 0))
            .phoneNumber("5700876")
            .build();
    modelMapper.addConverter((Converter<CarWashDTO, CarWash>) mappingContext -> {
        CarWashDTO source = mappingContext.getSource();
        CarWash destination = mappingContext.getDestination();
        destination.setId(source.getId());
        destination.setFirstShift(source.getFirstShift() == null ? null : Time.valueOf(source.getFirstShift()));
        destination.setSecondShift(source.getSecondShift() == null ? null : Time.valueOf(source.getSecondShift()));
        destination.setEnable(true);
        destination.setAddress(source.getAddress());
        destination.setBoxCount(source.getBoxCount());
        destination.setName(source.getName());
        destination.setDateOfCreation(source.getDateOfCreation());
        return …我在 Spring 中使用 ModelMapper。在我的控制器类中,我正在自动装配 ModelMapper bean:
@Autowired
private ModelMapper mapper;
我想在我的控制器方法中在模型类和 DTO 之间进行显式映射,例如:
modelMapper.addMappings(mapper -> {
  mapper.map(src -> src.getBillingAddress().getStreet(),
      Destination::setBillingStreet);
  mapper.map(src -> src.getBillingAddress().getCity(),
      Destination::setBillingCity);
});
然后使用映射器来映射类。
我的问题是,在每个控制器方法调用中添加显式映射是否正确?对象模型映射器会开始增加内存大小吗?
另一种解决方案是在创建 ModelMapper bean 时只添加一次映射,但我认为将映射逻辑放在 bean 配置中不是一个好的决定。
让我们假设我上课MySource:
public class MySource {
    public String fieldA;
    public String fieldB;
    public MySource(String A, String B) {
       this.fieldA = A;
       this.fieldB = B;
    }
}
我想把它翻译成对象MyTarget:
public class MyTarget {
    public String fieldA;
    public String fieldB;
}
使用默认的ModelMapper设置我可以通过以下方式实现它:
ModelMapper modelMapper = new ModelMapper();
MySource src = new MySource("A field", "B field");
MyTarget trg = modelMapper.map(src, MyTarget.class); //success! fields are copied
然而,它可能发生,即MySource对象将是null.在这种情况下,MyTarget也将null:
    ModelMapper modelMapper = new ModelMapper();
    MySource src = null; …我在我的休息应用程序中使用 ModelMapper。
我必须将列表转换为列表。
这是我的代码:
 Converter<List<UserRole>,List<String>> listConverter = new Converter<List<UserRole>, List<String>>() {
    public List<String> convert(MappingContext<List<UserRole>, List<String>> context) {
        List<String> target = new ArrayList<String>();
        List<UserRole> userRoles = context.getSource();
        for (UserRole userRole : userRoles) {
            target.add(userRole.getRole().getName());
        }
        return target;
    }
};
PropertyMap<User, UserDTO> propertiesForConvertToDto = new PropertyMap<User, UserDTO>() {
    protected void configure() {
        using(listConverter).map(source.getUserRoles()).setRoles(null);
    }
};
当我运行应用程序时,我收到此错误:
    HTTP Status 500 - Request processing failed; nested exception is org.modelmapper.MappingException: ModelMapper mapping errors:
type Exception report
message Request processing failed; nested exception is org.modelmapper.MappingException: ModelMapper …我想映射到一个只有一个带有 3 个参数的构造函数的源目标。我收到以下错误:
无法实例化目标 com.novasol.bookingflow.api.entities.order.Rate 的实例。确保 com.novasol.bookingflow.api.entities.order.Rate 有一个非私有的无参数构造函数。
当我在源目标中插入一个 no-args 构造函数时,它会起作用,但这会导致类的滥用,所以我宁愿不这样做。
我试过使用转换器,但这似乎不起作用:
Converter<RateDTO, Rate> rateConverter = new AbstractConverter<RateDTO, Rate>() {
    protected Rate convert(RateDTO source) {
        CurrencyAndAmount price = new CurrencyAndAmount(source.getPrice().getCurrencyCode(), source.getPrice().getAmount());
        Rate rate = new Rate(price, source.getPaymentDate(), source.getPaymentId());
        return rate;
    }
};
是否可以告诉模型映射器如何映射到没有无参数构造函数的目的地?
我正在使用 ModelMapper 将一些对象转换为复杂的 DTO,反之亦然。
尽管我试图理解文档,但我发现很难理解何时使用 Converter、Provider 或 AbstractConverter。
现在,例如,如果我想将字符串属性转换为目标 DTO 内的小 DTO,我将在抽象转换器内手动执行此操作。
例如:
dest.setAddressDTO(new AddressDTO(source.getStreet(), source.getNumber()));
虽然这是正确的方法吗?我什么时候应该使用提供程序?
如果我想用条件设置属性,我可以在转换器中使用 Conditional 还是仅在使用 PropertyMap 时?
此外,使用相同的 modelMapper 实例来转换几种不同类型的对象是否是一个好习惯?
提前致谢
我想在UserDTO和之间映射User,但要排除一个字段city。我该怎么做,因为虽然这种方法行得通,但它不能:
ModelMapper modelMapper = new ModelMapper();
modelMapper.typeMap(UserDTO.class,User.class).addMappings(mp -> {
    mp.skip(User::setCity);
});
与干净的架构一样,我们必须定义EntitiesinDomain层和ModelsinData层。现在我面临的问题是当我们将其作为存储库中的请求对象传递时将其转换entities为。models
这是描述实体(棕色)和模型(绿色)之间关系的图表。
现在,将实体转换为模型的最简单方法是什么dart,因为实现一个mapper字段然后从另一个字段复制一个字段似乎是一项非常乏味的工作,并且当类中有嵌套对象时(i.e. UserProfile data in below diagram)需要花费大量时间。那么是否存在任何现有的库或更好的方法可以无缝转换entities为model.
abstract class Mapper<E, D> {
  D mapFromEntity(E type);
  E mapToEntity(D type);
}