I have the following mapping, to which I pass an existing entity to be overwritten.
@Mapping(source = "fullName", target = "name")
PersonEntity toEntity(PersonRecord record, @MappingTarget PersonEntity existingEntity);
In a few cases, there is no existing entity i.e. it is null and causes an exception.
I would lilke Mapstruct to create a new target instance if (and only if) existingEntity
is null.
One solution is to have two mapping methods, one with and one without @MappingTarget, but I would like to avoid the code duplication, as the mapping is otherwise the same.
I am calling the mapper from a generic context, where I do not know the target type, meaning I cannot do the null check and create a new target myself before calling the mapper.
I have tried:
@BeforeMapping
default void ensureTargetExists(PersonRecord record, @MappingTarget PersonEntity existingEntity)
{
if(Objects.isNull(existingEntity))
{
existingEntity = new PersonEntity();
}
}
but the generated implementation just calls this method by value and when it returns, existingEntity
is null again.
Is there any way of achieving this?
For example, is there a way of telling Mapstruct to inline the code of ensureTargetExists
into the generated mapping method?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744707753a4589156.html
评论列表(0条)