【发布时间】:2018-01-19 02:28:22
【问题描述】:
我有带有字段的实体类:
- 客户端发件人;
- 客户收件人;
我有带字段的 DTO 类:
- 长发件人ID;
- 长收件人ID;
如果我这样做:
@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()))")
})
您能建议我如何映射它们吗?
【问题讨论】:
-
这是一个错误。我为此创建了#1148