如何使用modelmapper将多个字段映射到一个目标字段

时间:2017-11-15 00:49:26

标签: java modelmapper

如何将多个字段映射/合并到一个字段中?就像将.validatefirstname连接到目标lastname

fullname

1 个答案:

答案 0 :(得分:3)

您可以在public class ModelMapperConfigTest { @Test public void should_validate() { new ModelMapperConfig().modelMapper().validate(); } @Data public static class Person { private String firstname; private String lastname; } @Data public static class PersonDto { private String firstname; private String lastname; private String fullname; } // Test data @Test public void should_map_multiple_fields_into_one() { ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); // TODO: Configure modelmapper to merge the two fields // test that all fields are mapped modelMapper.validate(); // test that the age is calculated Person person = new Person(); person.setFirstname("Marilyn"); person.setLastname("Monroe"); PersonDto personDto = modelMapper.map(person, PersonDto.class); assertEquals(personDto.fullname, "Marilyn Monroe"); } // This method should be used for mapping. In real, this could be a service call private String generateFullname(String firstname, String lastname) { return firstname + " " + lastname; } } 内使用Converter

只需像这样配置你的映射器:

PropertyMap