4

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

THis is my code for 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 dont know where to associate those classes when I create a User which has groups in (I cannot use ORM). I made it in the create method of User, and also manage transactions there through Spring. Is this correct? Or should I put that code in the userRepository or in a Service?

Thanks!

4

3 回答 3

3

根据 Eric Evans 的书,多对多的关联会使您的模型过于复杂。尝试用 2 个多对一关联替换它们。多对多关联的一部分总是比其他部分具有更大的商业价值。

在您的情况下,我将保留 2 个聚合 -UserGroup,其中User聚合负责持有一堆GroupReferences.

于 2011-08-11T05:15:28.360 回答
1

卢卡斯,我会:

1) 创建一个用户工厂,它可以接收应该与新用户关联的组。工厂可以使用 addGroup 方法进行关联。

2) 从 User 类中删除对 UserRepository 的引用。

于 2011-08-10T16:40:39.020 回答
1

我在 User 的 create 方法中实现了它,并且还通过 Spring 管理了那里的事务。这个对吗?

此逻辑的正确性取决于存储库的编写方式及其合同。如果存储库不会保留任何关系,那么它可能是存储库设计不佳的标志。我希望存储库能够实现必要的逻辑来存储实体关联,而不仅仅是实体的简单属性。

基于 ORM 解决方案的存储库可以通过级联持久性事件使这更容易,但在您的情况下,它可能会导致两个存储库中的代码重复(我假设您也有GroupRepository)。如果您决定哪个实体拥有关系,然后让相应的存储库保持关联,则可能会更好。因此,关联中的任何更改都应仅由拥有关联的实体完成(在您的情况下似乎是User这样,并且通过推断UserRepository应该管理关联)。

于 2011-08-10T16:47:12.120 回答