如何使用MapStruct来简化Spring应用程序中复杂DTO层的Map?

wi3ka0sx  于 2023-05-27  发布在  Spring
关注(0)|答案(1)|浏览(135)

如何使用MapStructMap多层DTO:

// Menu.java
public class Menu {
    private String path;
    private String name;
    private String component;
    private String redirect;
    private MenuMeta meta; // <- This 
}
// MenuMata.java
public class MenuMeta {
    private String title;
    private String icon;
    private Boolean hideMenu;
    private String currentActiveMenu;
    private Boolean ignoreKeepAlive;
    private Boolean showMenu;
    private String frameSrc;
    private Boolean hideBreadcrumb;
}
// MenuSaveQuery
public class MenuSaveQuery {
    private Long parentId;
    private String path;
    private String name;
    private String component;
    private String redirect;
    private String title;
    private String icon;
    private Boolean hideMenu;
    private String currentActiveMenu;
    private Boolean ignoreKeepAlive;
    private Boolean showMenu;
    private String frameSrc;
    private Boolean hideBreadcrumb;
}

我想把上面的两个类投影到下面的这个类中,但是我不知道怎么做。
像这样:

public Menu save(MenuSaveQuery query);

我知道我可以用@Mapping targetsource来一一Map,但是这样太麻烦了。有什么简单的方法吗

mwkjh3gx

mwkjh3gx1#

根据Mapstruct文档,有一个解决方案:https://mapstruct.org/documentation/stable/reference/pdf/mapstruct-reference-guide.pdf
如果不想显式命名嵌套源bean的所有属性,可以使用。作为目标。

@Mapper
public interface CustomerMapper {
    @Mapping( target = "name", source = "record.name" )
    @Mapping( target = ".", source = "record" )
    @Mapping( target = ".", source = "account" )
 Customer customerDtoToCustomer(CustomerDto customerDto);
}

生成的代码将直接将CustomerDto.record中的每个属性Map到Customer,而不需要手动命名它们中的任何一个。Customer.account也是如此。

相关问题