I'm writing an application and following the Data Mapper pattern.
I've ended up in a situation where two data mappers depend on each other. Specifically, I have a Parent
type that has Child
objects. When a parent is modified, it needs to get a list of its children and process them a bit. When a child is modified, it has to check the state of its parent. This leads to classes structured like so:
class ParentMapper {
ParentMapper(ChildMapper childMapper) { ... }
void save(Parent p) {
Child[] children = childMapper.list(p.getId());
}
}
class ChildMapper {
ChildMapper(ParentMapper parentMapper) { ... }
void save(Child c) {
Parent p = parentMapper.get(c.getParentId());
}
}
I can't create either without the other being created.
What is a good way to handle this? While I'm not required to use the Data Mapper pattern, I have found it to be a nice clean abstraction.
This is Java with Guice, for reference.