Search code examples
javacqrsaxon

Projecting @AggregateVersion in Axon


I'm using annotation @AggregateVersion in my aggregate to handle optimistic concurrency. In order to receive this version in request, anybody that makes a request needs first to get current version from my view projection. Is there some standard way to project this version field (since, I guess, this should not be included inside events DTO)?

So far, the only thing I can think of is just to count projected events in projection and increase version +1 each time I project one of events.


Solution

  • Jasper's MetaData suggestion would've gotten you there, but there's an easier solution to this problem.

    Axon uses the notion of ParameterResolvers (sadly only very shortly described here, but in more depth here) to resolve things like the command/event/query, MetaData or a MetaDataValue. You can however also have the framework resolve the sequence number which in for an Event Sourced Aggregate is the aggregate version. You can do this by adding an @SequenceNumber annotated Long parameter in an Event Handling function.

    Hence, you can write an event handler like so:

    @EventHandler
    public void on(YourEvent event, @SequenceNumber Long aggregateVersion) {
        // Update the query model And the aggregate version
    }
    

    Having said that, this will obviously require you to handle all events from an aggregate in the event handling component to be able to update the version accordingly. Luckily, Axon will recognize if you handle parent classes of an event payload. Thus, if you define an event class hierarchy, ensuring all events from a given aggregate implement interface MyAggregateEvent. You can thus write an Event Handler like this to cover all remaining events just for aggregate version updates which you'd otherwise wouldn't be interested in:

    @EventHandler
    public void on(MyAggregateEvent event, @SequenceNumber Long aggregateVersion) {
        // Update the aggregate version only
    }
    

    Hope this helps!


    P.S. I just noticed that the Handling Events page of the reference guide does state the @SequenceNumber annotation.