How should we create new aggregate roots in cqrs architecture? In this example I want to create new aggregate root AR2 that holds reference to first one AR1.
I'm creating AR2 using AR1 method as starting point. So far I see few options:
- Inside method in AR1
createAr2RootOpt1
I could callnew AR2()
and save this object to db imediatelly using domain service that has acces to repository. I could emit event in first aggregate root eg.
SholdCreateAR2Event
and then have stateless saga that reacts on this and issues commandCreateAR2Command
which is then handled and actually creates AR2 and emitsAR2CreatedEvent
. In case of using event sourcingSholdCreateAR2Event
would not be preserved in event store, since it does not affect the state of first aggregate root. (Or should we still save this in event store?)class AR1{ Integer id; DomainService ds; //OPTION 1 void createAr2RootOpt1(){ AR2 ar2 = new AR2(); ds.saveToRepo(ar2); } //OPTION 2 void createAr2RootOpt2(){ publishEvent(new SholdCreateAR2Event()); //we don't need this event. Shoud it still be preserved in event store? } } class AR2{ Integer id; Integer ar1Id; void handle(CreateAR2Command command){ //init this AR with values and save publishEvent(AR2CreatedEvent()); //used for projections afterwards and saved inside AR2 event store } } class Saga{ void handle(SholdCreateAR2Event ev){ emitCommand(new CreateAR2Command()); } }
Which is more proper way to do this?