Fizik26
Fizik26

Reputation: 839

How to apply List in one field with MapStruct?

I have this POJO :

public class PlayerDto {

    private Long id;
    private String name;
    private String past;

}

And I have this entity :

public class Player {

    private Long id;
    private String name;
    private List<String> past;

}

How can I map the List<String> past into the String past of the DTO wih MapStruct ? For example the List is containing [ Monty , Boto , Flaouri ] and the String of the DTO has to contain "Monty, Boto, Flaouri" in a single String.

This classic way doesn't work with the target and source :

@Mappings({
            @Mapping(target = "past", source = "past"),
})
PlayerDto entityToDto(final Player entity);

Thanks

Upvotes: 1

Views: 3859

Answers (1)

Andrianekena Moise
Andrianekena Moise

Reputation: 1068

I guess you need to define a default method in your mapper interface to handle data conversion from List<String> to String. Mapstruct will automatically use the default method.

The default method signature for your mapping should be like this :

String map(List<String> past)

Example :

default String map(List<String> past) {
    return past.stream().collect(Collectors.joining(","));
}

Upvotes: 3

Related Questions