有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何删除Axon上的AggregateMember?

我有一个聚合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框架删除OrganizationDeliveryAddress聚合成员


共 (1) 个答案

  1. # 1 楼答案

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

    要“删除”一个AggregateMember,您应该执行与添加它相反的操作,这意味着您可以在聚合上有一个@EventSourcingHandler方法来监听OrganizationDeliveryAddressRemovedEvent。此方法将负责在您的AggregateMember(deliveryAddresses)或更好的Map上找到正确的DeliveryAddress,您将在下面看到,并将其从中删除。伪代码可以是这样的:

    // 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());
    }