为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕田峪7331174 2024-01-05 11:01:38
我有两节课。请求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);但这不起作用,它说它不能将字符串转换为长整型。我请求对此的解决方案或更好的方法。
查看完整描述

1 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

如果您想手动执行映射(特别适合不同的对象)

您可以查看不同对象映射属性映射的文档,

您可以通过使用方法引用来匹配源 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

@AllArgsConstructor

class Source {

    private Long id;

    private String name;

}


@Data

@NoArgsConstructor

@AllArgsConstructor

class Destination {

    private String name;

}


查看完整回答
反对 回复 2024-01-05
  • 1 回答
  • 0 关注
  • 44 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信