1 回答

TA貢獻1887條經驗 獲得超5個贊
如果您想手動執(zhí)行映射(特別適合不同的對象)
您可以查看不同對象映射屬性映射的文檔,
您可以通過使用方法引用來匹配源 getter 和目標 setter 來定義屬性映射。
typeMap.addMapping(Source::getFirstName,?Destination::setName);
源類型和目標類型不需要匹配。
?typeMap.addMapping(Source::getAge,?Destination::setAgeString);
如果您不想逐個字段進行映射以避免樣板代碼
您可以配置跳過映射器,以避免將某些字段映射到目標模型:
modelMapper.addMappings(mapper?->?mapper.skip(Entity::setId));
我已經為您的案例創(chuàng)建了一個測試,映射適用于雙方,無需配置任何內容:
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;
}
添加回答
舉報