aggregatedomain-driven-designcqrsaxon

Creating an Aggregates leads to an CommandExecutionException: OUT_OF_RANGE: [AXONIQ-2000] Invalid sequence number 0 for aggregate 0, expected 1


I am new to Axon and trying to get my first program to run with Quarkus and Axon. I just want to walk through a Command, CommandHandler, Aggregate, Event, EventHandler and EventSourcingHandler. When I am trying to create a new Aggregate through a CreateAggregateCommand and an AggregateCreatedEvent I always get the following Exception:

AxonServerRemoteCommandHandlingException{message=An exception was thrown by the remote message handling component: OUT_OF_RANGE: [AXONIQ-2000] Invalid sequence number 0 for aggregate 0, expected 1, errorCode='AXONIQ-4002', server='28856@31NP00158'}

My Code is really straight forward: This is my Command:

public class CreateAggregateCommand {

    @TargetAggregateIdentifier
    private final int id;

    public CreateAggregateCommand(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }
}

This Is my Aggregate:

@AggregateRoot
public class MyAggregate {

    @AggregateIdentifier
    int aggregateId;

    private static Logger logger = LoggerFactory.getLogger(MyAggregate.class);

    @CommandHandler
    @CreationPolicy(AggregateCreationPolicy.CREATE_IF_MISSING)
    public void handle(CreateAggregateCommand createAggregateCommand) {
        logger.info("Enter CommandHandler. AggregateId is: " + aggregateId);
        apply(new AggregateCreatedEvent(createAggregateCommand.getId()));
    }

    @EventSourcingHandler
    public void on (AggregateCreatedEvent event) {
        logger.info("Enter EventsourcingHandler. The event-id: " + event.getId());
        this.aggregateId = event.getId();
    }
}

This is my Event:

public class AggregateCreatedEvent {

    private final int id;

    public AggregateCreatedEvent(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }
}

And finally this is my EventHandler:

    public class EventHandlers {

    Logger logger = LoggerFactory.getLogger(EventHandlers.class);

    @EventHandler
    public void handleCreateAggregate(AggregateCreatedEvent createAggregateEvent) {
        logger.info("Enter EventHandler");
    }
}

I also tried to place the @CommandHandler onto a constructor, with the same exception result. I am struggling since many hours, made resarch but I do not see my mistake.


Solution

  • This exception occurs when there already is an event for the given aggregate identifier (0 in this case), and another event is created for an aggregate that was just created. Either try using a different aggregate identifier, or use a regular instance method to indicate yoh wabt Axon to load an aggregate.

    Also note that int is far from ideal as type for an identifier. Usually aggregate identifiers are UUID or String (with a random uuid as content)