Two Aggregates in CommandHandler leads to

In my engagement to clone an Aggregate with an Entity I failed somewhat.

java.lang.IllegalStateException: Cannot register new aggregate. This entity is already part of another aggregate

here is what I do:


newRecipe = new Recipe(oldRecipe)

In Recipe.ctx() I have bunch of Entities:

map= Map // which I copy in the same way with CopyConstructor pattern
map.add(new Ingredient(sourceIngredient))

apply(new RecipeCloned(map))

And this is why the “This entity is already part of another aggregate” happens.
it seems that i must instance a new ENTITY only after an apply()?

But this means that I can not use a single event to bear all data to be cloned but, need apply() a bunch of IngredientInserted events after the clone command.

I’d prefer one clean single Event starting up my cloned Recipe.
What do you think?

Thanks, Roland

Hi Roland,

the code looks good. You’re doing a deep copy of the aggregate, which is the way to do it. In the “Ingredient” constructor, which fields do you copy? The field “AbstractEventSourcedEntity#aggregateRoot” should not be copied into the new aggregate. Axon will autodetect entities in the fields of your aggregate, right after applying the event to the aggregate root. Looking at your code, I don’t see any problems there.

One remark about your design: I notice you’re copying entities into events. It might work for you, but in general I advise to exclusively use immutable (value) objects in Events. You might get into strange problems if an entity is mutated while an event handler is processing an event containing that entity.



I’v found the problem: apply() registers the new entity and then a second time in Fixture#when().
By switching to Value Objects in the Event as you suggested it works.