【问题标题】:Good practice, transfer id or DTO object?好习惯,转移id还是DTO对象?
【发布时间】:2017-09-28 21:40:50
【问题描述】:

我在程序中有一个方法负责下载消息

MessageReceived getMessageReceived(Long messageId,Long userId);

此时,它需要一个 long 值。整个方法是这样的

@Override
public List<MessageReceived> getMessagesReceived(
        @NotNull @Min(1) Long userId
) throws ResourceNotFoundException {
    log.info("Called with userId {}", userId);

    Optional<UserEntity> user = this.userRepository.findByIdAndEnabledTrue(userId);
    user.orElseThrow(() -> new ResourceNotFoundException("No user found with id " + userId));

    return this.messageRepository.findByRecipientAndIsVisibleForRecipientTrueOrderByIdDesc(user.get())
            .stream()
            .map(MessageEntity::getReceivedDTO)
            .collect(Collectors.toList());
}

更好的做法是:发送用户 ID 本身或 dto USER 对象。在控制器中,我可以指定 dto 对象方法,但我选择了 ID,因为在我看来,没有必要在此处发送带有附加字段的整个 DTO。你怎么看?

【问题讨论】:

  • 可以,如果你不需要,就别寄了。
  • 好的。谢谢。验证的情况或具有给定 ID 的消息属于用户关于此 ID 的情况如何。需要在控制器或服务中进行验证?
  • 我会尽可能地限制控制器中的逻辑。您可以显式进行完整性检查,也可以使用 id >= 1 之类的注释。然后让服务处理无效的 id。

标签: java spring spring-mvc spring-boot dto


【解决方案1】:

我认为这并不重要,只要你始终如一。如果您要在此处传递 ID,那么您应该养成始终传递 id 而不是 DTO 的习惯。

我个人的偏好是始终传递 ID。

【讨论】:

  • 好的。谢谢。验证的情况或具有给定 ID 的消息属于用户关于此 ID 的情况如何。需要在控制器或服务中进行验证?
猜你喜欢
  • 2016-04-26
  • 2010-10-16
  • 1970-01-01
  • 2013-07-17
  • 2011-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-31
相关资源
最近更新 更多