MapStruct:将2个对象映射到第3个对象 [英] MapStruct: Mapping 2 objects to a 3rd one

查看:2911
本文介绍了MapStruct:将2个对象映射到第3个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Object1和Object2。现在,我想映射object3,其属性来自1& 2。

I have Object1 and Object2. Now, I want to map object3, with attributes from 1 & 2.

说,我有2个对象:

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

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

Now, with these, I want to map that in

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

其中,first_name& last_name将来自User对象
和city&来自地址对象的状态。

Where, first_name & last_name will be from User object and city & state from Address object.

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

但是,目前,我正在这样做

However, currently, I'm doing like this

@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()中写入映射。

But, here, I have to manually write the mapping in addressToView().

因此,有什么方法可以避免那个?

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

推荐答案

您可以使用多个源参数声明一个映射方法,并在 @Mapping 注释:

You can declare a mapping method with several source parameters and refer to the properties of all these parameters in your @Mapping annotations:

@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属性名称在源和目标中匹配,不需要映射它们。

As the "city" and "state" property names match in source and target, there is no need for mapping them.

另见在参考文档中定义映射器以获取更多详细信息。

Also see the chapter "Defining a mapper" in the reference documentation for more details.

这篇关于MapStruct:将2个对象映射到第3个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆