我有带字段的实体类:
- 客户发件人;
- 客户收件人;
我有带字段的 DTO 类:
- 长的senderId;
- 长recipientId;
如果我这样做:
@Mappings({ @Mapping(source = "senderId", target = "sender.id"), @Mapping(source = "recipientId", target = "recipient.id") })
Mapstruct 将生成如下代码:
public Entity toEntity(DTO) {
//...
entity.setSender( dtoToClient( dto ) );
entity.setRecipient( dtoToClient( dto ) );
//...
protected Client dtoToClient(Dto dto) {
Client client = new Client();
client.setId( dto.getRecipientId() ); // mapstruct takes recipient id for sender and recipient
return client;
}
}
Mapstruct 为发件人和收件人使用收件人 ID 而不是收件人 ID 来创建客户端收件人和发件人 ID 来创建客户端发件人。
所以我发现更好的方法是使用在我看来不太优雅的表达式:
@Mappings({
@Mapping(target = "sender", expression = "java(createClientById(dto.getSenderId()))"),
@Mapping(target = "recipient", expression = "java(createClientById(dto.getRecipientId()))")
})
你能建议我如何映射它们吗?
最佳答案
在解决错误之前,您需要定义方法并使用 qualifiedBy
或 qualifiedByName
。关于那里的更多信息here在文档中。
您的映射器应如下所示:
@Mapper
public interface MyMapper {
@Mappings({
@Mapping(source = "dto", target = "sender", qualifiedByName = "sender"),
@Mapping(source = "dto", target = "recipient", qualifiedByName = "recipient")
})
Entity toEntity(Dto dto);
@Named("sender")
@Mapping(source = "senderId", target = "id")
Client toClient(Dto dto);
@Named("recipient")
@Mapping(source = "recipientId", target = "id")
Client toClientRecipient(Dto dto);
}
关于java - Mapstruct 从字符串到具有相同类型的多个字段的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42951058/