拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 在这个涉及将物体类实体转换为DTO实体的用例中,如何正确使用流映射()?

在这个涉及将物体类实体转换为DTO实体的用例中,如何正确使用流映射()?

白鹭 - 2022-02-22 1965 0 0

我正在开发一个 Spring Boot 应用程序,并且我正在尝试使用更现代的(Java 8 构造),但我发现尝试对现有代码实施以下更改时遇到了一些困难。

我有以下服务方法:

@Override
public Optional<User> activateDeactivateUser(int userId, boolean isActive) throws NotFoundException {
    
    Optional<User> retrievedUser = this.userRepository.findById(userId);
    
    if(retrievedUser.isEmpty())
        throw new NotFoundException(String.format("The user having ID or email %s was not found", userId));
    
    
    return Optional.ofNullable(retrievedUser) 
            .map((user) -> { 
                log.info(String.format("****** USER E-MAIL *******", user.get().getEmail()));
                
                user.get().set_active(isActive);
                this.userRepository.save(user.get());
                
                return user;
                })
            .orElseThrow(() -> new NotFoundException(String.format("The user having ID or email %s was not found", userId)));
}

如您所见,此方法回传一个Optional物件。首先,我不确定回传Optional是一个好习惯(因为如果它是空的,我会抛出并处理NotFoundException)。

但主要问题是我的User类是一个物体类(我使用的是 Hibernate,所以它包含表映射)我想更改以前的方法以检索UserDTO物件。

为了将User实体转换为UserDTO实体,我将此ConversionService注入到我的服务类中(我在其他地方使用过)

@Autowired
ConversionService conversionService;

我的主要问题是,在我以前的方法中,我使用的是map()运算子。我曾尝试以这种方式改变之前的服务方式:

@Override
public UserDTO activateDeactivateUser(int userId, boolean isActive) throws NotFoundException {
    
    Optional<User> retrievedUser = this.userRepository.findById(userId);
    User userToBeUpdated = null;
    
    if(retrievedUser.isEmpty())
        throw new NotFoundException(String.format("The user having ID or email %s was not found", userId));
    else
        userToBeUpdated = retrievedUser.get(); 
    
    return userToBeUpdated
            .map((userToBeUpdated) -> { 
                log.info(String.format("****** USER E-MAIL *******", userToBeUpdated.getEmail()));
                
                userToBeUpdated.set_active(isActive);
                this.userRepository.save(userToBeUpdated);
                
                return userToBeUpdated;
                })
            .orElseThrow(() -> new NotFoundException(String.format("The user having ID or email %s was not found", userId)));

}

我的想法是使用map()方法来转换一个物件(我的User物件为UserDTO物件并将其保存在应用函式的数据库中)。

首先 Eclipse 它在map()方法呼叫上给了我以下错误:

由于我对流的经验很少,我不知道它是否是map()使用的正确用例。这是因为(也在第一个方法实作中,效果很好)我没有实作真正的物件转换,但我正在更改物件栏位的值,然后将其保存到数据库中。在第二种情况下(我的服务方法的第二个版本),我必须从User转换为UsertDTO

我错过了什么?在这个用例中使用map()是否合法,还是强制使用 map() 的预期方式?什么可能是解决这个问题的好方法?

uj5u.com热心网友回复:

在第一个示例中,该if宣告完全没有意义。您可以完全洗掉它,因为如果回传的实际值不是 ,则将执行mapon 此外,还有一个代码重复OptionalnullNotFoundException

@Override
public UserDTO activateDeactivateUser(int userId, boolean isActive) throws NotFoundException {
    return this.userRepository.findById(userId)
            .map((userToBeUpdated) -> {
                log.info(String.format("****** USER E-MAIL *******", userToBeUpdated.getEmail()));

                userToBeUpdated.set_active(isActive);
                this.userRepository.save(userToBeUpdated);

                return userToBeUpdated;
            })
            .orElseThrow(() -> new NotFoundException(String.format("The user having ID or email %s was not found", userId)));

}

虽然,这段代码可能有效,但问题是我们在map. 当我们将其作为映射操作的高阶函式传递时,建议使用纯函式。使用这样的东西可能会更好:

@Override
public User activateDeactivateUser(int userId, boolean isActive) throws NotFoundException {

    User retrievedUser = this.userRepository.findById(userId)
            .orElseThrow(() -> new NotFoundException(String.format("The user having ID or email %s was not found", userId)));

    retrievedUser.set_active(isActive);
    this.userRepository.save(retrievedUser);

    return retrievedUser;
}

现在,您的第二个示例更有问题。这个片段是无效的,在逻辑上没有意义:

userToBeUpdated
            .map((userToBeUpdated) -> {...})

User类是一个休眠物体,它很可能没有map实作它的方法,为什么会呢?在 Java 中,通常流和可选项为map. 它用于对流/可选封装的每个物件应用一些转换。您可能想查看选项的档案以了解更多关于它们的信息。

我相信你想在这里做的是:

@Override
public UserDTO activateDeactivateUser(int userId, boolean isActive) throws NotFoundException {

    User retrievedUser = this.userRepository.findById(userId)
            .orElseThrow(() -> new NotFoundException(String.format("The user having ID or email %s was not found", userId)));

    retrievedUser.set_active(isActive);
    this.userRepository.save(retrievedUser);

    return conversionService.convert(retrievedUser);
}

我希望它ConversionService有类似convert方法的东西,它接受一个物体物件并回传一个 DTO。

与该问题无关的其他一些注释:

  • 请遵守 Java 编码标准。在 Java 中,我们不使用蛇形大小写进行方法呼叫。userToBeUpdated.set_active(isActive);应该是这样的userToBeUpdated.setActive(isActive);
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *