2

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: enter image description here

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?

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
Albert
  • 113
  • 2
  • 13
  • Spring Data does this for you. – Boris the Spider Apr 18 '21 at 22:33
  • "*Is approach like this acceptable?*" - Yes. This is the [interface segregation principle](https://en.wikipedia.org/wiki/Interface_segregation_principle) and belongs to the [SOLID principles](https://en.wikipedia.org/wiki/SOLID). – Turing85 Apr 18 '21 at 22:34
  • 1
    Correction: It is the [Separation of Concerns principle](https://en.wikipedia.org/wiki/Separation_of_concerns), not the Interface segregation principle. In essence, the persistence is a separate concern and thus should be separated out (entirely, including data classes for the specific persistence layer). – Turing85 Apr 18 '21 at 22:45
  • @BoristheSpider But in order to use `Spring Data JPA` or `Spring Data MongoDb` you still need to have these dedicated Entities/Documents. – Albert Apr 18 '21 at 22:51

1 Answers1

1

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.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736