Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapStruct: List mapping is not using single mapping when annotated by @Named

Tags:

java

mapstruct

I have the following Mapper

@Mapper
@Named("RoleBaseMapper")
public interface RoleBaseMapper {

    @Mapping(target = "code", source = "name")
    @Named("mapToBase")
    RoleGuiBaseDto mapToBase(Role role);

    @Named("MapListToBase")
    List<RoleGuiBaseDto> mapListToBase(List<Role> roles);
}

What I expect is that mapListToBase will use mapToBase to map each entry in the list. But when I see the generated code, I have the following

@Override
public List<RoleGuiBaseDto> mapListToBase(List<Role> roles) {
    if ( roles == null ) {
        return null;
    }

    List<RoleGuiBaseDto> list = new ArrayList<RoleGuiBaseDto>( roles.size() );
    for ( Role role : roles ) {
        list.add( roleToRoleGuiBaseDto( role ) );
    }

    return list;
}

protected RoleGuiBaseDto roleToRoleGuiBaseDto(Role role) {
    if ( role == null ) {
        return null;
    }

    RoleGuiBaseDto roleGuiBaseDto = new RoleGuiBaseDto();

    roleGuiBaseDto.setId( role.getId() );
    roleGuiBaseDto.setDescription( role.getDescription() );

    return roleGuiBaseDto;
}

A new mapper method is created and is used instead of using mapToBase.

How can I tell mapListToBase to use mapToBase.

NB : Things works well without @Named.

like image 769
Radouane ROUFID Avatar asked Mar 24 '26 22:03

Radouane ROUFID


1 Answers

You need to qualify the mapping method when using @Named (using @IterableMapping#qualifiedByName):

@Mapper
@Named("RoleBaseMapper")
public interface RoleBaseMapper {

    @Mapping(target = "code", source = "name")
    @Named("mapToBase")
    RoleGuiBaseDto mapToBase(Role role);

    @IterableMapping(qualifiedByName = "mapToBase")
    @Named("MapListToBase")
    List<RoleGuiBaseDto> mapListToBase(List<Role> roles);
}
like image 197
jannis Avatar answered Mar 27 '26 11:03

jannis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!