Search code examples
javamappingdtomapstruct

MapStruct DTO property


I need to have a property on my DTO like idEncrypted because they can pass me only encrypted, however, I need to map the decrypt id as I find on DB. I already have a decrypt method, but I don't know how to map it and ignore the idEncrypted.

@Data
@EqualsAndHashCode(callSuper=false)
@NoArgsConstructor
public class MyDTO {  

    private String idEncrypted;
  
    ...
    ...

}

I don't know where to do the conversion

idDecrypted = Long.parseLong(MyUtils.decrypt(idEncrypted));

Solution

  • You can write your own custom qualified method for doing the decryption.

    e.g.

    @Mapper
    public MyMapper {
    
        @Mapping(target = "id", source = "idEncrypted", qualifiedByName = "decryptId")
        MyEntity map(MyDTO dto);
    
        @Named("decryptId")
        default Long decryptId(String id) {
            return id != null ? Long.parseLong(MyUtils.decrypt(id)) : null;
        }
    }