I've read that accessing repository from aggregate root considered bad practice. If it is, than consider following example:
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?
...
}
}
How will I persist username to database if I don't have access to repository from aggregate root?
I see it like this:
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);
}
}
Or I've missed something in DDD concepts?