如何删除 Axon 上的 AggregateMember?

How can I delete an AggregateMember on Axon?

我有一个集合 Organization,它可以有多个地址。因此,我们将此 OrganizationDeliveryAddress 建模为聚合成员。在 OrganizationDeliveryAddress 上,我们为实体本身命令和事件源处理程序。

这是我当前的实现:

@Aggregate
public class Organization {

  private @AggregateIdentifier
  @NonNull UUID organizationId;

  @AggregateMember
  private final List<OrganizationDeliveryAddress> deliveryAddresses = new ArrayList<>();

  @CommandHandler
  public UUID on(AddOrganizationDeliveryAddressCommand command) {
    val addressId = UUID.randomUUID();
    val event = new OrganizationDeliveryAddressAddedEvent(command.getOrganizationId(), addressId, command.getAddress());
    AggregateLifecycle.apply(event);
    return addressId;
  }

  @EventSourcingHandler
  public void on(OrganizationDeliveryAddressAddedEvent event) {

    val address = new OrganizationDeliveryAddress(event.getOrganizationDeliveryAddressId(), false);
    deliveryAddresses.add(address);
  }

}

 

public class OrganizationDeliveryAddress {

  private @EntityId
  @NonNull UUID organizationDeliveryAddressId;
  
  @CommandHandler
  public void on(RemoveOrganizationDeliveryAddressCommand command) {
    AggregateLifecycle.apply(new OrganizationDeliveryAddressRemovedEvent(command.getOrganizationId(),
        command.getOrganizationDeliveryAddressId()));
  }

  @EventSourcingHandler
  public void on(@SuppressWarnings("unused") OrganizationDeliveryAddressRemovedEvent event) {
    if (organizationDeliveryAddressId.equals(event.getOrganizationDeliveryAddressId())) {
      AggregateLifecycle.markDeleted();
    }
  }

}

我们想删除其中一个地址,但看起来不仅仅是地址,整个集合都被删除了。

所以这是我的问题:如何指示 Axon Framework 删除 OrganizationDeliveryAddress 聚合成员?

AggregateMember 本身不是聚合,而只是另一个聚合的成员。这就是为什么如果您调用 AggregateLifecycle.markDeleted(); 它会将聚合本身标记为已删除。

到 'delete' 一个 AggregateMember 你应该做与添加它相反的事情,这意味着你可以在你的聚合上有一个 @EventSourcingHandler 方法来监听 OrganizationDeliveryAddressRemovedEvent。此方法负责在您的 AggregateMember (deliveryAddresses) 上找到正确的 DeliveryAddress,甚至更好的是 Map,您将在下面看到,然后只需将其从中删除。 pseudo-code 可能是这样的:

// Organization.java
...
@AggregateMember
private final Map<UUID, OrganizationDeliveryAddress> deliveryAddressItToDeliveryAddress = new HashMap<>();
...
@EventSourcingHandler
public void on(@SuppressWarnings("unused") OrganizationDeliveryAddressRemovedEvent event) {
    Assert.isTrue(deliveryAddressItToDeliveryAddress.containsKey(event.getOrganizationDeliveryAddressId()), "We do not know about this address");
    deliveryAddressItToDeliveryAddress.remove(event.getOrganizationDeliveryAddressId());
}