gpt4 book ai didi

java - DDD : is accessing repository from aggregate root considered bad practice?

转载 作者:行者123 更新时间:2023-12-01 07:20:27 25 4
gpt4 key购买 nike

我读到从聚合根访问存储库被认为是不好的做法。如果是,请考虑以下示例:

class User {
private String username;
public void changeUsername(String newUsrname) {
// How will I persist username to database if I don't have access to repository from aggregate root?
...
}
}

如果我无权访问存储库,如何将用户名保留到数据库来自聚合根?

我是这样看的:

class User {
private String username;
private UserRepository userRepository;
public User(UserRepository userRepository) {
this.userRepository = userRepository;
}

public void changeUserName(String newUsername) {
this.username = newUserName;
userRepository.save(this);
}
}

或者我错过了 DDD 概念中的某些内容?

最佳答案

How will I persist username to database if I don't have access to repository from aggregate root?

当前的实践通常在应用程序组件中处理 I/O,而不是在域模型中。

Application {
void when(ChangeUserName command) {
User user = this.userRepository.getUserById(command.userId);
user.changeName(command.name);
this.userRepository.save(user);
}
}

推荐阅读:Vladimir Khorikov关于领域模型隔离。

关于java - DDD : is accessing repository from aggregate root considered bad practice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39896123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com