本文介绍了如果Dto具有使用MapStruct的ID,则将dto映射到从数据库检索到的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MapStruct 进行dto <-> entity映射.相同的映射器用于从dtos 创建 更新实体.完成对dto ID的验证,以了解是否必须创建一个新实体(id == null)还是应该从数据库中检索它(id!= null).

I'm using MapStruct to make dto <-> entity mapping. The same mappers are used to create and update entities from dtos. A verification of the dto's id is done to know whether a new entity must be created (id == null) or it should be retrieved from database (id != null) .

我实际上在使用 MapperDecorator 作为解决方法.示例:

I'm actually using MapperDecorator as a workaround. Example :

@Mapper
@DecoratedWith(UserAccountDecorator.class)
public interface UserAccountMapper {

    UserAccountDto map(User user);

    User map(UserAccountDto dto);

    User map(UserAccountDto dto, @MappingTarget User user);
}

装饰器

public abstract class UserAccountDecorator implements UserAccountMapper {

    @Autowired
    @Qualifier("delegate")
    private UserAccountMapper delegate;

    @Autowired
    private UserRepository userRepository;

    @Override
    public User map(UserAccountDto dto) {
        if (dto == null) {
            return null;
        }

        User user = new User();
        if (dto.getId() != null) {
            user = userRepository.findOne(dto.getId());
        }

        return delegate.map(dto, user);
    }

}

但是,由于必须为每个映射器创建一个装饰器,因此该解决方案变得繁重.

But this solution becomes heavy due to the fact that a decorator must be created for each mapper.

有什么好的解决方案吗?

Is there any good solution to perform that ?

我正在使用:

  1. MapStruct: 1.1.0

推荐答案

我通过遵循 Gunnar 的建议解决了我的问题>在.

I solved my problem by following the advice of Gunnar in the comment.

我转到了 MapStruct 1.2.0 .Beta1 并创建了一个如下所示的UserMapperResolver

I moved to MapStruct 1.2.0.Beta1 and created a UserMapperResolver like below

@Component
public class UserMapperResolver {

    @Autowired
    private UserRepository userRepository;

    @ObjectFactory
    public User resolve(BaseUserDto dto, @TargetType Class<User> type) {
        return dto != null && dto.getId() != null ? userRepository.findOne(dto.getId()) : new User();
    }

}

然后在UserMapper中使用哪个:

Which I use then in my UserMapper :

@Mapper(uses = { UserMapperResolver.class })
public interface BaseUserMapper {

    BaseUserDto map(User user);

    User map(BaseUserDto baseUser);

}

现在生成的代码是:

@Override
    public User map(BaseUserDto baseUser) {
        if ( baseUser == null ) {
            return null;
        }

        User user = userMapperResolver.resolve( baseUser, User.class );

        user.setId( baseUser.getId() );
        user.setSocialMediaProvider( baseUser.getSocialMediaProvider() );
...
}

效果很好!

这篇关于如果Dto具有使用MapStruct的ID,则将dto映射到从数据库检索到的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 14:11
查看更多