2

I am struggling to map a string object from source(Relation.class) and to a List of target(RelationListDTO.class) .

Relation.java

   public class Relation {

    private String name;
    private String email;
    private String completeAddress;

    // getters and setters
}

RelationListDTO.java

public class RelationListDTO {
        private String name;
        private String email;
        private List<Address> address;

        // getters and setters
    }

Address.java

public class Address{
private String street;
private String city;
// getters and setters
}

Mapper class

@Mapper

public interface RelationMapper {

    @Mapping(source = "completeAddress", target = "address.get(0).city")
            RelationListDTO relationToListDto(Relation relation);
} 

But it is not working. Could anyone please help.

2 Answers 2

7

What you are trying to do using MapStruct is not possible. Because MapStruct doesn't work with run time objects. MapStruct only generated plain java code for mapping two beans. And I find your requirement is little unique. You have a list of Addresses but want to map only city from source object? You can still do like this

@Mapping( target = "address", source = "completeAddress")
RelationListDTO relationToListDto(Relation relation);

// MapStruct will know to use this method to map between a `String` and `List<Address>`
default List<Address> mapAddress(String relation){
      //create new arraylist
      // create new AddressObject and set completeAddress to address.city
     // add that to list and return list

}
Sign up to request clarification or add additional context in comments.

Comments

1

Not sure if this was possible at the time of the accepted answer but I had the same problem as you and ended up doing it this way.

@Mapper(imports = Collections.class)
public interface RelationMapper {
    @Mapping(expression = "java(Collections.singletonList(relation.getCompleteAddress()))", target = "address")
            RelationListDTO relationToListDto(Relation relation);
}

1 Comment

This is also the preferred way to concat strings as mentioned in github.com/mapstruct/mapstruct/issues/624

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.