In 95% of examples I see, people are adding @Entity
or @Document
annotations to their domain objects.
I would like to create an app in which I can easily change persistence layer.
It should be possible to switch in settings from SQL DB
to e.x. MongoDB
etc.
I want to keep my domain objects completely independent from persistence layer.
I have thought about something like this:
Where Item
is a domain object.
public interface ItemsRepository {
List<Item> getItems();
}
Each ItemsRepository
implementation has it's own dedicated persistence layer object. For SQL it will be let's say ItemEntity
class, for Mongo ItemDocument
class. And each persistence object has conversion from and to domain object.
Is approach like this acceptable? If not, what are the best industry patterns to solve that problem?
I would consider this a good application of the Dependency Inversion Principle. I'm not saying this to counter the other comments to the question, but rather to highlight that this sort of design seems defensible when looked at from more than one perspective. I often design code bases according to a similar structure. Yes, I'd say that it's more than acceptable.