Map a dto to an entity retrieved from database if Dto has Id using MapStruct

后端 未结 2 618
执笔经年
执笔经年 2020-12-31 20:08

I\'m using MapStruct to make dto <-> entity mapping. The same mappers are used to create and update en

2条回答
  •  说谎
    说谎 (楼主)
    2020-12-31 20:35

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

    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 type) {
            return dto != null && dto.getId() != null ? userRepository.findOne(dto.getId()) : new User();
        }
    
    }
    

    Which I use then in my UserMapper :

    @Mapper(uses = { UserMapperResolver.class })
    public interface BaseUserMapper {
    
        BaseUserDto map(User user);
    
        User map(BaseUserDto baseUser);
    
    }
    

    The generated code is now :

    @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() );
    ...
    }
    

    Works well !

提交回复
热议问题