Al Grant
Al Grant

Reputation: 2354

MapStruct @AfterMapping scope

With MapStruct does @AfterMapping have to apply to every method on the class?

Should each EntityDTO have its own mapper class?

Upvotes: 0

Views: 4608

Answers (1)

GJohannes
GJohannes

Reputation: 1753

Not Each EntityDTO should have its own MapperClass. Each Entity should have its own class. Considering you have the Entity User. The your Mapper can look something like this:

@Mapper(config = MappingConfig.class)
public interface UserMapper {

  @Mapping(target = "someValue", ignore = true)
  UserDTO2 mapToEntity(User userEntity);

  UserDTO1 mapToEntity(User userEntity);

  @AfterMapping
  default void setAfterMappingAnlageToDto(User source, @MappingTarget UserDTO1 target) {
      // your logic for the first DTO
  }

  @AfterMapping
  default void setAfterMappingAnlageToDto(User source, @MappingTarget UserDTO2 target) {
      // your logic for the second DTO
  }

}

As you can see, it is possible to tell @AfterMapping to only be used with a specific DTOs.

Upvotes: 1

Related Questions