Reputation: 81
I have a situation where I have another DTO in inside a DTO to which I have to map to its corresponding entity.
I am using mapstruct and I already have AnotherEntityMapper already existing.
DTO
public class EntityDTO {
private AnotherEntityDTO anotherEntityDTO;
// other fields
}
Entity
@Entity
public class Entity {
private AnotherEntity anotherEntity;
// other fields
}
How to change the EntityMapper interface, so that I can map anotherEntityDTO to anotherEntity?
Thanks.
Upvotes: 2
Views: 6054
Reputation: 21403
It really depends which version of MapStruct you are using. If you are using 1.2.0.Beta or higher they you can just define the nested properties on your EntityMapper
interface:
@Mapper
public interface EntityMapper {
@Mapping(target = "anotherEntity", source = "anotherEntityDTO")
@Mapping(target = "anotherEntity.propE", source = "anotherEntityDTO.propD")
Entity map(EntityDDTO dto);
}
Another option (and a must if you are using version less than 1.2.0.Beta) is to add a new Method in your EntityMapper
like:
@Mapper
public interface EntityMapper {
@Mapping(target = "anotherEntity", source = "anotherEntityDTO")
Entity map(EntityDDTO dto);
@Mapping(target = "propE", source = "propD")
AnotherEntity map(AnotherEntityDTO);
}
or you can define a new Mapper AnotherEntityMapper
for the AnotherEntity
and use @Mapper(uses = {AnotherEntityMapper.class})
:
@Mapper
public interface AnotherEntityMapper {
@Mapping(target = "propE", source = "propD")
AnotherEntity map(AnotherEntityDTO);
}
@Mapper(uses = {AnotherEntityMapper.class}
public interface EntityMapper {
@Mapping(target = "anotherEntity", source = "anotherEntityDTO")
Entity map(EntityDDTO dto);
}
It really depends on your use case. If you need to do mappings between AnotherEntity
and AnotherEntityDTO
on other places, I would suggest to use a new interface so you can reuse it where you need it
Upvotes: 6