I have an Entity and EntityGroup as 2 separate aggregates. I need to be able to access Entity#id without knowing EntityGroup#id, so I can’t put Entity inside EntityGroup as an @AggregateMember because, in order to access an Entity, you have to provide both Entity#id and EntityGroup#id. Hence, I simply have Entity#groupId and EntityGroup#entityIds.
This is how I create an Entity: in an external non-aggregate class, I first check if there is a groupId provided, and if not, I send and wait for CreateEntityGroupCommand with random id, secondly, I send and wait for CreateEntityCommand with that groupId, then, inside @EventSourcingHandler of Entity, it sends and waits for AssignEntityToGroupCommand (which may throw “already exists”).
From this answer, I know that I should probably put AssignEntityToGroupCommand outside of the @EventSourcingHandler to not lock Entity but I feel like I have to, because if the entity already exists in the group then Entity must not be created.
It feels more natural to put this kind of validation inside the command handler of the Entity but then I would get that an Entity is assigned to Group before it was even created