Luiz E.
Luiz E.

Reputation: 7279

domain events are only published before save

I have an aggregate root like this:

public class Room extends AbstractAggregateRoot implements Serializable {
  // lots of code
  @OneToMany(mappedBy = "room", cascade = {CascadeType.MERGE, CascadeType.PERSIST,
      CascadeType.REMOVE})
  private List<Message> messages = new ArrayList<>();

  public void sendMessage(Message message) {
    message.setRoom(this);
    messages.add(message);
    registerEvent(new MessageSavedEvent((message)));
  }
}

and I'm creating a message like this:

Room room = roomRepository.findByUid(uid);
room.sendMessage(MessageFactory.createMessage(params.getContent(), sender));
roomRepository.save(room);

thing is that the event is being published before the message is saved, so in my message saved handler, the id and other things like createdAt are null. I know that I can publish events manually through ApplicationContext but I would be violating DDD not publishing events from the aggregator. Is ther any other thing I can do?

Upvotes: 0

Views: 1636

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 82000

Spring Data doesn't offer out of the box support for this. But JPA has post persist events: http://www.objectdb.com/java/jpa/persistence/event

So I guess what you could do is write a listener for that, triggering the publishing of events.

One challenge is that JPA might replace your instance, and it won't copy fields over that don't get persisted. This might lead to your messages being gone once the post-persist event fires. So you might want to use the existing infrastructure t store the message during the persist somewhere independent of the aggregate root and then publish them afterwards.

Upvotes: 1

Related Questions