Skip to content
Advertisement

MapStruct: Change Target of Mapping based on Source contents?

I’m trying to represent an international address in a class object using MapStruct that maps it from a PDF form.

The address will have a country, if this country is America then the address must have a state. If the country is not America then the address must have a province. I have separate variables for state and province, but want to map something like:

@Mapping(target="userCountry", source="Form_User_Country")
@Mapping(target="userState", source="Form_User_State_or_Province")
@Mapping(target="userProvince", source="Form_User_State_or_Province")

The state or province of the user is represented by one field in the form, but two separate variables in the DTO.

How can I make it so if Form_User_Country=”USA”, then the comments of Form_User_State_or_Province map to userState, but to map the contents to userProvince instead if the Form_User_Country!=”USA”?

Advertisement

Answer

You could try some expressions. I haven’t tried it, but I think it should be something like this; here, arg is the name of the method argument you’re converting (so rename that).

@Mapping(target="userCountry", source="Form_User_Country")
@Mapping(target="userState", expression="java("USA".equals(arg.getForm_User_Country()) ? arg.getForm_User_State_or_Province() : null)")
@Mapping(target="userProvince", expression="java(!"USA".equals(arg.getForm_User_Country()) ? arg.getForm_User_State_or_Province() : null)")
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement