Mapstruct: Create new mapping target if @MappingTarget is null - Stack Overflow

I have the following mapping, to which I pass an existing entity to be overwritten.@Mapping(source = &

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信