public class AggregateRoot {
private Integer id;
private Set<Child> children;
}
public class Child {
private Integer id;
private String name;
}
Imagine that you need to save Child
and to send his ID to the some external system. In DDD you will save child with code similar to this:
AggregateRoot aggregateRoot = aggregateRootRepository.getById(id);
Child child = new Child();
child.setName("Sun");
aggregateRoot.addChild(child);
aggregateRootRepository.save(aggregateRoot);
externalService.postSavedChildId(child.getId());
Of course child.getId()
will return null because it is not in persistence context. Any idea how this case should be handled in DDD?
There are two problems in your case, which I will address separately:
DDD suggests that aggregate roots carry global IDs, while "inner" entity IDs have only local significance. So you should not expose the inner ID alone, as it will not uniquely address the entity.
Using DB-generated IDs does not fit well with DDD for the reasons you experienced. The best approach is usually to use generated random IDs. This answer has more information about the topic.
From reading your question, I get the impression that you take a rather DB-centric approach (using DB-generated IDs is one indication of that). When using DDD, try to focus on the domain model first and build the DB infrastructure around it.
Imagine that you need to save Child and to send his ID to the some external system
You cannot do it. Entities within an aggregate have local identities, which means it is impossible to access these entities from the outside the aggregate. The only entity accessible from the outside of an aggregate, meaning having a global identity, is the aggregate root.
So it seems the entity, whose ids you want to provide to an external system, is actually an aggregate root.
Another question is, why do you expose the database ids of entities of one system to another system? Systems should not depend on the database ids of other systems. They should use business ids instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With