带有对象列表的 ModelMapper propertyMap 到 responseDTO

ModelMapper propertyMap with List of objects to a responseDTO

我是 modelMapper 的新手,当我尝试将实体对象列表添加到 responseDTO 时遇到了问题。

用户 - 实体 UserResponseDTO - 响应 DTO

我为 propertyMap 做了以下配置。

        modelMapper.addMappings(new PropertyMap<List<User>, UserResponseDTO>() {
            @Override
            protected void configure() {
                map().setName(source.get(0).getName());
                map().setEmail(source.get(0).getEmail());
                map().setUserRole(source.get(0).getUserRole());
                map().setLanguage(source.get(0).getLanguage());
                map().setTimeZone(source.get(0).getTimeZone());
                // ....have more mapping ahead
            }
        });

但它给出了以下错误:

org.modelmapper.ConfigurationException: ModelMapper configuration errors:

1) Invalid source method java.util.List.get(). Ensure that method has zero parameters and does not return void.

2) Invalid source method java.util.List.get(). Ensure that method has zero parameters and does not return void.

3) Invalid source method java.util.List.get(). Ensure that method has zero parameters and does not return void.

4) Invalid source method java.util.List.get(). Ensure that method has zero parameters and does not return void.

5) Invalid source method java.util.List.get(). Ensure that method has zero parameters and does not return void.

谁能告诉我如何解决这个问题?

正如错误信息所说:

Ensure that method has zero parameters

这是因为(下面摘自here

You receive these errors because PropertyMap restricts what you can do inside configure().

我发现很难理解您实际要映射的内容,因为您似乎只想将 User 的一些列表展平为包含仅来自单个用户的数据的 DTO,即列表中的第一个(如果不为空!)。也许你没有做你应该做的事,或者你做事的方式不对。至少看起来你不需要任何特殊的映射。

假设您的 UserUserResponseDTO 会像(简化!):

@Getter @Setter
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String name;
    private String email;
}

@Getter
@Setter
public class UserResponseDTO {
    private String name;
    private String email;
}

那么映射单个用户就像:

new ModelMapper().map(users.get(0), UserResponseDTO.class);

如果您想映射谁列表,例如:

new ModelMapper().map(users, UserListResponseDTO.class)

那么您的 UserListResponseDTO 将简单地类似于:

@SuppressWarnings("serial")
public class UserListResponseDTO extends ArrayList<UserResponseDTO> {}

或者如果您碰巧需要 return 一个只有第一个用户的列表:

new ModelMapper()..map(Arrays.asList(users.get(0)), UserListResponseDTO.class)