0

How i can initialize List in field and add in this list some values?

    @Mapper(componentModel = "spring")
public interface MapStructAdapter {

  @Mapping(source = "some", target = "some")
  @Mapping(expression = "java(new java.util.ArrayList<LegalEntity>())", target = "legalEntities")
  @Mapping(expression = "java(new my.some.package.LegalEntity())", target = "getLegalEntities().add()")
  @Mapping(source = "entityShortName", target = "legalEntities.legalEntity.shortName")
  Representative convert(Message message);
}

2 Answers 2

1

You should be able to add your own conversion methods in a mapper.

https://mapstruct.org/documentation/stable/reference/html/#adding-custom-methods

Example,

@Mapper(componentModel = "spring")
public interface MapStructAdapter {

    @Mapping(source = "some", target = "some")
    @Mapping(source = "entityShortName", target = "legalEntities")
    Representative convert(Message message);

    default List<LegalEntity> toLegalEntities(String entityShortName) {
        LegalEntity legalEntity = new LegalEntity();
        legalEntity.setShortName(entityShortName);
        return Collections.singletonList(legalEntity);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Very complete answer (includes link to docs and sample code)! Could you explain, how the mapping knows when to use the custom method toLegalEntities. Is there any declaration or naming-convention in place?
Thank, this is a nice, if i have one field in LegalEntity, but if a have more, then one? @Mapping(source = "entityShortName", target = "legalEntities.legalEntity.shortName") @Mapping(source = "entityLongName", target = "legalEntities.legalEntity.LongName") for example
@hc_dev, as far as I understand custom methods take precedence over implicit conversion and MapStruct find is by looking at method argument and return type.
@Petr, that would be easier if you posted the structure of your models. However, it seems a bit too complicated and probably the first you could do is reconsider the structure of your objects. I don't have the answer off the top of my head although I'm pretty sure MapStruct can do this as well.
0

Just add a (factory)method to your mapper. No argument and return the List. Can be a default method or a method in s class you @Mapper#uses

Comments

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.