[英]Mapstruct convert field to object field
我想用 mapStruct 映射两个对象
public class EntityA
{
@Id
private String id;
@Column
private String anotherField
第二个对象带有一个对象一个参数
public class ABC
{
private final ObjectXYZ identification;
// another fields
public class ObjectXYZ
{
private final String identification;
我的映射器:
@Mapper
public interface ObjectMapper
{
@Mapping(target = "identification", source = "identification", qualifiedByName = "ObjectXYZ")
ABC toABC(EntityA entity);
EntityA toEntityA(Material material);
@Named("ObjectXYZ")
@Mapping(target = "identification", source = "identification")
ObjectXYZ toObjectXYZ(String identification);
}
我如何将EntityA.id
映射到ABC.identification.identification
对象定义:
public class EntityA {
private String id;
private String anotherField;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAnotherField() {
return anotherField;
}
}
public class ABC {
private final ObjectXYZ identification;
private final String anotherField;
public ABC(ObjectXYZ identification, String anotherField) {
this.identification = identification;
this.anotherField = anotherField;
}
public String getAnotherField() {
return anotherField;
}
public ObjectXYZ getIdentification() {
return identification;
}
}
public class ObjectXYZ
{
private String identification;
public ObjectXYZ(String identification) {
this.identification = identification;
}
public String getIdentification() {
return identification;
}
}
映射器:
Mapstruct 自动确定映射的方法或构造函数,您只需指定正确的目标\源属性。
@Mapper
public interface ObjectMapper
{
@Mapping(target = "identification", source = "entity.id")
@Mapping(target = "anotherField", source = "entity.anotherField")
ABC toABC(EntityA entity);
@Mapping(target = "identification", source = "identification")
ObjectXYZ toObjectXYZ(String identification);
}
生成的代码:
public class ObjectMapperImpl implements ObjectMapper {
@Override
public ABC toABC(EntityA entity) {
if ( entity == null ) {
return null;
}
ObjectXYZ identification = null;
String anotherField = null;
identification = toObjectXYZ( entity.getId() );
anotherField = entity.getAnotherField();
ABC aBC = new ABC( identification, anotherField );
return aBC;
}
@Override
public ObjectXYZ toObjectXYZ(String identification) {
if ( identification == null ) {
return null;
}
String identification1 = null;
identification1 = identification;
ObjectXYZ objectXYZ = new ObjectXYZ( identification1 );
return objectXYZ;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.