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

后端 未结 2 633
执笔经年
执笔经年 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条回答
  •  萌比男神i
    2020-12-31 20:57

    MapStruct alone can't do that. However, with some generics and a main abstract class you can make your life easier.

    You need one generic interface. It must not be annotated with @Mapper, because if it is MapStruct will try to generate an implementation and it will fail. It cannot generate generic mappers.

    public interface GenericMapper {
    
        DTO map(E entity);
    
        E map(DTO dto);
    
        E map(DTO dto, @MappingTarget E entity);
    }
    

    Then you need one abstract class where you'll have your logic.

    public abstract class AbstractGenericMapper implements GenericMapper {
    
        @Autowired
        private Repository repository;
    
        @Override
        public final E map (DTO dto) {
            if (dto == null) {
                return null;
            }
    
            // You can also use a Java 8 Supplier and pass it down the constructor
            E entity = newInstance();
            if (dto.getId() != null) {
                user = repository.findOne(dto.getId());
            }
    
            return map(dto, entity);
        }
    
        protected abstract E newInstance();
    }
    

    And then each of your mappers will only need to extend this abstract class.

    @Mapper
    public abstract class UserAccountMapper extends AbstractGenericMapper {
    
        protected User newInstance() {
            return new User();
        }
    }
    

    MapStruct will then generate an implementation for your mapper and you will only have to extend the AbstractGenericMapper for the future. Of course you will need to adapt the generic parameters so you can at least get the id from the via some interface maybe. If you have different type of ids then you will have to add that generic parameter to the AbstractGenericMapper as well.

提交回复
热议问题