Posts made in septembre, 2021
Mapper une liste de DTO avec mapstruct
Imaginons que nous avons une entité « phone » avec un shemas strucuturé et un phoneDto qui met à plat cette donnée. Si on veut pouvoir mapper proprement avec mapstruct on peut faire comme ceci : Un PhoneMapper Java @Mapper public interface PhoneMapper { @Mapping(source = "indicator.indicator", target = "indicator") @Mapping(source = "type", target = "phoneType") @Mapping(source = "number", target = "number") InnerPhoneNumber mapToKafka(Phone phone); @Mapping(source = "indicator", target = "code") PhoneDto mapFromKafka(InnerPhoneNumber phone); @Named("phoneListToInnerPhoneNumberList") List<InnerPhoneNumber> mapListToKafka(List<Phone> phones); @Named("InnerPhoneNumberListToPhoneDto") List<InnerPhoneNumber> mapListFromKafka(List<Phone> phones); } 1234567891011121314151617 @Mapperpublic interface PhoneMapper { @Mapping(source = "indicator.indicator", target = "indicator") @Mapping(source = "type", target = "phoneType") @Mapping(source = "number", target = "number") InnerPhoneNumber mapToKafka(Phone phone); @Mapping(source = "indicator", target = "code") PhoneDto mapFromKafka(InnerPhoneNumber phone); @Named("phoneListToInnerPhoneNumberList") List<InnerPhoneNumber> mapListToKafka(List<Phone> phones); @Named("InnerPhoneNumberListToPhoneDto") List<InnerPhoneNumber> mapListFromKafka(List<Phone> phones);} ensuite on peut réutiliser dans un autre mapper, par exemple CustomerMapper Java @Mapper(uses = {PhoneMapper.class}) public interface CustomerMapper { @Mapping(target = ID_CUSTOMER_WPS, source = TECHNICAL_CODE) @Mapping(target = "phoneNumbers", source = "phoneNumberList", qualifiedByName = "InnerPhoneNumberListToPhoneDto") CustomerUpdateDto mapUpdateArtemis(CustomerUpdatedFromArtemis customerFromArtemis); } 12345678 @Mapper(uses = {PhoneMapper.class})public interface CustomerMapper { @Mapping(target = ID_CUSTOMER_WPS, source = TECHNICAL_CODE)@Mapping(target = "phoneNumbers", source = "phoneNumberList", qualifiedByName = "InnerPhoneNumberListToPhoneDto")CustomerUpdateDto mapUpdateArtemis(CustomerUpdatedFromArtemis customerFromArtemis); } Après on peut tester ça très rapidement avec assertj. Bonne...
Read More