I have two API entities (EntityA
and EntityB
) that implement BaseEntity
.
Both entities have the nullable parameter identifier
.
@Value
@Builder(builderClassName = "Builder")
public class EntityA implements BaseEntity {
String identifier;
...
}
@Value
@Builder(builderClassName = "Builder")
public class EntityB implements BaseEntity {
String identifier;
...
}
I have POJO as well with externalId
parameter. This field value should include the prefix of 4 characters of the source's identifier.
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class Pojo {
private String externalId;
...
}
I want to map the APIs values to existing POJO PojoEntity
, using ModelMapper
. However,
- source getter and destination setter are not match.
- source's value should be modified.
I can set the value post-factum, on an already mapped POJO.
public Pojo mapEntityAToPojo(EntityA entity, Pojo pojo) {
modelMapper.map(entity, pojo);
Optional.ofNullable(entity.getIdentifier()).ifPresent(
identifier -> pojo.setExternalId(getIdentifierAlphaNumericPrefix(identifier)));
return pojo;
}
public Pojo mapEntityBToPojo(EntityB entity, Pojo pojo) {
modelMapper.map(entity, pojo);
Optional.ofNullable(entity.getIdentifier()).ifPresent(
identifier -> pojo.setExternalId(getIdentifierAlphaNumericPrefix(identifier)));
return pojo;
}
private String getIdentifierAlphaNumericPrefix(String identifier) {
return identifier.replaceAll("[^a-zA-Z0-9]", "").substring(0, 4);
}
But I'm sure, there is a more elegant way, to configure model mapper.
Any suggestions?