Let's say I have the following Aggregate Root:
class Order {
private Collection<OrderItem> items;
...
public void updateQuantity(int itemId, int quantity) { ... }
}
And let's say I use plain SQL to persist it. The question is: how do I persist Order and its items without exposing the collection? I see several ways which I don't like:
1) Add a method that returns the copied collection. I don't like it, because we need to make copies of each item as well (since it is Entity and can be changed) which is another challenge on its own.
2) Add getters for every property of items:
class Order {
public int getQuantity(int itemId) { ... }
}
It is better since no one from outside cannot change the root's nested entities. But it can blow the root's class with tons of dummy getters.
3) Use the Hibernate way: get the items through java's reflection in the repository. That's "cheating". Also I am thinking about the way of creating DTO's as well, so I need a legit way to read the values.
4) Make the field to use default modifier and put the repository implementation (and the DTO's assembler as well) to the same package so that it will have access to the fields. Don't like it because repository implementation is not part of the domain.
I prefer the second approach, but there might be some other way I am missing?