java - Is it possible to implicitly map nested properties in MapStruct by convention to a flat property? - Stack Overflow

I'm using MapStruct to map between my entity and DTO classes. I have a nested property that I want

I'm using MapStruct to map between my entity and DTO classes. I have a nested property that I want to map without explicitly defining the @Mapping annotation for each nested property. I was wondering if there is a way to configure MapStruct to handle this implicitly by convention. I could find a matching configuration from the docs.

Here is a simplified version of my code:

@Mapper  
public interface CompanyMapper {  
  
    CompanyMapper INSTANCE = Mappers.getMapper(CompanyMapper.class);  
  
    // I want to avoid defining this @Mapping annotation  
    // @Mapping(source = "country.name", target = "countryName")  ► works but is to complicated for many properties in my opinion
   //@Mapping(target = ".", source = "country") ► not working, performs a flat mapping not country*   
    CompanyDto toDto(Company company);  
  
}  
  
@Data  
@Builder  
class Company {  
    private String name;  
    private Country country;  
}  
  
@Data  
@Builder  
class Country {  
    private String name;  
}  
  
@Data  
class CompanyDto {  
    private String name;  
    private String countryName;  
}  

@Test
void map() {
    var country = Country.builder()
            .name("France")
            .build();

    var company = Company.builder()
            .country(country)
            .name("Peugeot")
            .build();

    var companyDto = CompanyMapper.INSTANCE.toDto(company);
    assertEquals("Peugeot", companyDto.getName());
    assertEquals("France", companyDto.getCountryName());
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744933989a4601907.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信