Search code examples
javadomain-driven-designddd-repositories

DDD - Repository and many-to-many relationship


I am new to DDD and I am stuck here: I have a many-to-many relationship between two entities: User and Group. The relationship is not an Aggregate because a User can exist without a Group and a Group can exist without a User.

This is my code for the User class:

public class User {

    private List<Group> groups = new ArrayList<Group>();
    
    private UserRepository userRepository;

    public void create() throws Exception{
        userRepository.create(this);        
        
        // I have to update the groups with the user.
        for (Group group : groups) {
            group.update();
        }
    }
    
     public void addGroup(Group group){
        if (!groups.contains(group)) {
            groups.add(group);
            group.addUser(this);
         }
    }
}

The problem is that I don't know where to associate those classes when I create a User who has groups in (I cannot use ORM). I made it in the create method of User, and I also manage transactions there through Spring. Is this correct? Or should I put that code in the userRepository or in a Service?

Thanks!


Solution

  • I made it in the create method of User, and also manage transactions there through Spring. Is this correct?

    Correctness of this logic would depend on how the repository is written and it's contract. If the repository will not persist any relationships, then it could be a sign of a poorly designed repository. I would expect a repository to implement the necessary logic to store entity associations as well, and not just the simple properties of the entity.

    A repository based on an ORM solution would have made this easier by through the cascading of persistence events, but in your case, it might lead to duplication of code in both your repositories (I am assuming that you have a GroupRepository as well). It might be better if you decide on which entity owns the relationship, and then have the association persisted by the corresponding repository. Any changes in the association should therefore be done only by the entity that owns the association (it appears to be User in your case, and by inference the UserRepository should manage the association).