如何在模型映射器中跳过目标源中的属性?

我有两节课。请求DTO和实体。我想将 RequestDTO 映射到实体。在这种情况下,我想手动插入实体属性之一,这意味着该属性不在请求 DTO 中。如何使用 modelmapper 来实现这一点。


public class RequestDTO {


    private String priceType;


    private String batchType;

}


public class Entity {



    private long id;


    private String priceType;


    private String batchType;

}


Entity newEntity = modelMapper.map(requestDto, Entity.class);

但这不起作用,它说它不能将字符串转换为长整型。我请求对此的解决方案或更好的方法。


慕田峪7331174
浏览 49回答 1
1回答

慕工程0101907

如果您想手动执行映射(特别适合不同的对象)您可以查看不同对象映射属性映射的文档,您可以通过使用方法引用来匹配源 getter 和目标 setter 来定义属性映射。typeMap.addMapping(Source::getFirstName, Destination::setName);源类型和目标类型不需要匹配。 typeMap.addMapping(Source::getAge, Destination::setAgeString);如果您不想逐个字段进行映射以避免样板代码您可以配置跳过映射器,以避免将某些字段映射到目标模型:modelMapper.addMappings(mapper -> mapper.skip(Entity::setId));我已经为您的案例创建了一个测试,映射适用于双方,无需配置任何内容:import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import org.junit.Before;import org.junit.Test;import org.modelmapper.ModelMapper;import static junit.framework.TestCase.assertEquals;import static junit.framework.TestCase.assertNotNull;public class ModelMapperTest {    private ModelMapper modelMapper;    @Before    public void beforeTest() {        this.modelMapper = new ModelMapper();    }    @Test    public void fromSourceToDestination() {        Source source = new Source(1L, "Hello");        Destination destination = modelMapper.map(source, Destination.class);        assertNotNull(destination);        assertEquals("Hello", destination.getName());    }    @Test    public void fromDestinationToSource() {        Destination destination = new Destination("olleH");        Source source = modelMapper.map(destination, Source.class);        assertNotNull(source);        assertEquals("olleH", destination.getName());    }}@Data@NoArgsConstructor@AllArgsConstructorclass Source {    private Long id;    private String name;}@Data@NoArgsConstructor@AllArgsConstructorclass Destination {    private String name;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java