我有带有字段的实体类:
我有带字段的 DTO 类:
如果我喜欢这样:
@Mappings({ @Mapping(source = "senderId", target = "sender.id"), @Mapping(source = "recipientId", target = "recipient.id") })
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Mapstruct 为发件人和收件人而不是收件人 id 使用收件人 id 来创建客户端收件人和发件人 id 来创建客户端发件人。
所以我发现的更好的方法是使用就我所见并不那么优雅的表达式:
@Mappings({
@Mapping(target = "sender", expression = "java(createClientById(dto.getSenderId()))"),
@Mapping(target = "recipient", expression = "java(createClientById(dto.getRecipientId()))")
})
Run Code Online (Sandbox Code Playgroud)
你能建议我如何映射它们吗?
在错误解决之前,您需要定义方法并使用qualifedBy或qualifiedByName。文档中有关此处的更多信息。
您的映射器应如下所示:
@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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4817 次 |
| 最近记录: |