Skip to content

Instantly share code, notes, and snippets.

@sebhoss
Last active August 29, 2015 14:14
Show Gist options
  • Save sebhoss/26e8d3341455f0145fe4 to your computer and use it in GitHub Desktop.
Save sebhoss/26e8d3341455f0145fe4 to your computer and use it in GitHub Desktop.
Axon command/event handling
public class Person extends AbstractAnnotatedAggregateRoot<PersonId> {
@AggregateIdentifier
private PersonId id;
private String name;
private LocalDate birthday;
@CommandHandler
public Person(AddPersonCommand command) {
apply(new PersonAddedEvent(
command.getPersonId(),
command.getName(),
command.getBirthday()
)
);
}
@EventSourcingHandler
private void applyEvent(PersonAddedEvent event) {
id = event.getId();
name = event.getName();
birthday = event.getBirthday();
}
@CommandHandler
private void handleCommand(SetPersonNameCommand command) {
apply(new PersonNameSetEvent(command.getId(), command.getName());
// Why not the following?
apply(new PersonChangedEvent(id, command.getName(), birthday));
}
@EventSourcingHandler
private void applyEvent(PersonNameSetEvent event) {
name = event.getName();
}
}
@Service
public class PersonService {
// inject some stuff
@EventHandler
public void handleEvent(PersonAddedEvent event) {
db.insertInto(PERSON)
.set(PERSON.ID, event.getId())
.set(PERSON.NAME, event.getName())
.set(PERSON.BIRTHDAY, event.getBirthday())
.execute();
}
@EventHandler
public void handleEvent(PersonNameSetEvent event) {
db.update(PERSON)
.set(PERSON.NAME, event.getName())
.where(PERSON.ID.equal(event.getId())
.execute();
}
// Isn't it possible to replace every existing handler with the following?
@EventHandler
public void handleEvent(PersonChangedEvent event) {
// as classic relational table
db.update(PERSON)
.set(PERSON.NAME, event.getName())
.set(PERSON.BIRTHDAY, event.getBirthday())
.where(PERSON.ID.equal(event.getId())
.execute();
// .. or just as plain json?
String json = objectMapper.writeAsString(event);
db.update(PERSON_INFO)
.set(PERSON_INFO.DATA, json)
.where(PERSON_INFO.ID.equal(event.getId())
.execute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment