最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论