如何使用模型映射器从实体转换为 dto,并从字符串转换为 UUID [英] How to convert from entity to dto using model mapper , with conversion from string to UUID
本文介绍了如何使用模型映射器从实体转换为 dto,并从字符串转换为 UUID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一些帮助才能使用模型映射器将实体映射到 DTO.这是我的两个 pojo
I need some help to map Entity to DTO using Model Mapper. Here are my two pojos
@Data
public class ClientDTO {
private UUID id;
@NotNull
private String name;
private String description;
private String contactEmail;
}
@Data
@Entity
public class Client {
@Id
private String id;
@NotNull
private String name;
private String description;
@NotNull
private String contactEmail;
}
当我尝试在 Client 到 ClientDTO 之间转换时,id 呈现为 null.我尝试编写一个 PropertyMap 和一个转换器,但它们都不适合我.
When am trying to convert between Client to ClientDTO id is rendered as null. I tried writing a PropertyMap and a converter but none of them is working for me.
推荐答案
我浏览了文档并找到了问题的解决方案.这是解决方案.
I went through the documentation and was able to find a solution to the problem. Here is the soln.
初始化
private PropertyMap<Client, ClientDTO> clientMap;
private ModelMapper clientToClientDtoMapper;
定义PropertyMap 和转换器
clientToClientDtoMapper = new ModelMapper();
Converter<Client, UUID> uuidConverter = new AbstractConverter<Client, UUID>() {
protected UUID convert(Client source) {
return UUID.fromString(source.getId());
}
};
clientMap = new PropertyMap<Client, ClientDTO>() {
protected void configure() {
try {
using(uuidConverter).map(source).setId(null);
} catch (Exception ex) {
System.out.println("Error.");
}
}
};
clientToClientDtoMapper.addMappings(clientMap);
从实体到 DTO 的辅助方法
private ClientDTO convertToDto(Client client) {
ClientDTO clientDTO = clientToClientDtoMapper.map(client, ClientDTO.class);
return clientDTO;
}
这篇关于如何使用模型映射器从实体转换为 dto,并从字符串转换为 UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文