Spring boot 如何使用模型映射器将实体转换为dto,并将字符串转换为UUID

Spring boot 如何使用模型映射器将实体转换为dto,并将字符串转换为UUID,spring-boot,modelmapper,Spring Boot,Modelmapper,我需要一些帮助来使用模型映射器将实体映射到DTO。 这是我的两个POJO @Data public class ClientDTO { private UUID id; @NotNull private String name; private String description; private String contactEmail; } @Data @Entity public class Client { @Id private

我需要一些帮助来使用模型映射器将实体映射到DTO。 这是我的两个POJO

@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;
}

当我尝试在客户端客户端之间转换时,id被呈现为空。我试着写一个PropertyMap和一个转换器,但没有一个适合我。

我浏览了文档,找到了解决问题的方法。这是解决方案

初始化

private PropertyMap<Client, ClientDTO> clientMap;
private ModelMapper clientToClientDtoMapper;

嘿!因为这与我刚才问的一个问题非常相似,我很好奇,如果你有50个实体,并且希望它们都有一个UUID转换器,你会怎么做?我们必须为每个转换器创建一个转换器吗?或者,有没有一种方法可以通过只创建一个转换器来概括这一点。
        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);
    private ClientDTO convertToDto(Client client) {

        ClientDTO clientDTO = clientToClientDtoMapper.map(client, ClientDTO.class);
        return clientDTO;
    }