gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:36:53 26 4
gpt4 key购买 nike

如何将多个字段映射/合并为一个字段?就像将 firstnamelastname 连接到目的地 fullname 一样?

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;
}
}

最佳答案

为此,您可以在 PropertyMap 中使用 Converter

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

@Test
public void should_map_multiple_fields_into_one() {

ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

modelMapper.createTypeMap(Person.class, PersonDto.class)
.addMappings(
new PropertyMap<Person, PersonDto>() {
@Override
protected void configure() {
// define a converter that takes the whole "person"
using(ctx -> generateFullname(
((Person) ctx.getSource()).getFirstname(),
((Person) ctx.getSource()).getLastname())
)
// Map the compliete source here
.map(source, destination.getFullname());
}
});

// 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;
}

关于java - 如何使用 modelmapper 将多个字段映射到一个目标字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47297689/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com