MapStruct:将 2 个对象映射到第三个对象

MapStruct: Mapping 2 objects to a 3rd one

我有对象 1 和对象 2。现在,我想用 1 和 2 的属性映射 object3。

说,我有 2 个对象:

1. User: {first_name, last_name, id}
2. Address: {street, locality, city, state, pin, id}

现在,有了这些,我想将其映射到

User_View: {firstName, lastName, city, state}.

其中,first_name & last_name 将来自用户对象 和地址对象中的城市和州。

现在,我的问题是,该怎么做?

然而,目前,我是这样做的

@Mapper    
public abstract class UserViewMapper {
        @Mappings({
                    @Mapping(source = "first_name", target = "firstName"),
                    @Mapping(source = "last_name", target = "lastName"),
                    @Mapping(target = "city", ignore = true),
                    @Mapping(target = "state", ignore = true)

            })
            public abstract UserView userToView(User user);

        public UserView addressToView(UserView userView, Address address) {

                if (userView == null) {
                    return null;
                }

                if (address == null) {
                    return null;
                }

                userView.setCity(address.getCity());
                userView.setState(address.getState()); 

            return userView;

            }
    }

但是,在这里,我必须在 addressToView() 中手动编写映射。

因此,有什么办法可以避免这种情况吗?

或者,处理这种情况的首选方法是什么?

在使用 MapStruct 时,您缺少一个使用 @Mapper 注释的步骤。 @Mapper 将创建映射的实现。

您应该在此处查看文档 link http://mapstruct.org/documentation/stable/reference/html/

具体

  1. Defining a mapper

In this section you’ll learn how to define a bean mapper with MapStruct and which options you have to do so. 3.1 Basic mappings

To create a mapper simply define a Java interface with the required mapping method(s) and annotate it with the org.mapstruct.Mapper annotation:

@Mapper
public interface CarMapper {

    @Mappings({
        @Mapping(source = "make", target = "manufacturer"),
        @Mapping(source = "numberOfSeats", target = "seatCount")
    })
    CarDto carToCarDto(Car car);

    @Mapping(source = "name", target = "fullName")
    PersonDto personToPersonDto(Person person);
}

The @Mapper annotation causes the MapStruct code generator to create an implementation of the CarMapper interface during build-time.

您可以声明一个带有多个源参数的映射方法,并在您的 @Mapping 注释中引用所有这些参数的属性:

@Mapper
public abstract class UserViewMapper {

    @Mapping(source = "first_name", target = "user.firstName"),
    @Mapping(source = "last_name", target = "user.lastName"),
    public abstract UserView userAndAddressToView(User user, Address address);
}

由于 "city" 和 "state" 属性 名称在源和目标中匹配,因此不需要映射它们。

有关详细信息,请参阅参考文档中的 "Defining a mapper" 章。