I am building an application under DDD architecture, thus I have implemented rich domain objects that can also be entities. These entities can also have full access to (injected) repositories that can do add & remove operations on other objects/entities. So far, this all works without any problems.
But can side effects for objects/entities that are added or removed be programmed? For example, when an object/entity is removed, I want other objects to get informed about it, so they can (re)query the database for storing for example new totals.
At first impression I thought JPA lifecycle methods @PreRemove and @PostRemove could handle this situation. But after studying the JPA documentation, the possibilities of these lifecycle methods are very limited. It’s not allowed to refer to any other entities and neither are you allowd to run queries via the EntityManager.
An other solution could be to handle the remove & add operations always via their repository calls. In the repository the needed side effects can then be implemented in these methods. But this is still a leaky API, even if all calls are done via the repository (and not directly via an EntityManager) there still is the possibility that entities get removed by automatic JPA deletes that result from cascading or orpahed deletes. In those instances the side effects programmed in the repository, will not be called.
My questions: how can I best implement these kinds of side effects under a DDD architecture?