I'm working on a project Spring Boot project where there are two separate packages named domain
and persistence
.
The domain
package primarily contains the Domain Classes (designed based on the business requirements) whereas the persistence
package contains the repository interfaces defined by extending the repositories provided by Spring Data
.
I have used Spring Data JPA
annotations inside the domain classes and those classes are directly used when defining the repository interfaces as well. Everything works well here.
But the issues I have is that one could argue that domain classes do not need to know about the persistence implementation and domain classes should kept clean without polluting with Spring Data JPA
annotation. This makes me this that I should maybe use a different set of classes (let's say Entity classes with more or less attributes) to implement the persistence so that I can keep the domain classes clean. But if I do this;
Spring Data
repositories are going to work with theseEntity Classes
and I will not be able to use the interface based repositories out of the box since I will always have to map theEntity objects
returned by repositories toDomain Classes
.- I believe that at some point, I will introduce
DTOs
as well and when I reach this level, there will be too many mappings (Entity Classes
toDomain Classes
and thenDomain Classes
toDTOs
). I personally think this mapping will be an overhead in the long run.
Summary -
Should I maintain Domain Model Classes
and Entity Classes
separately or should I just use Domain Model Classes
along with Spring Data JPA
annotations and KISS?
CodePudding user response:
I think it is a mistake to separate the repository interfaces from the domain classes. Repositories are a part of the domain. Their implementation isn't, but you are not dealing with the implementation since that is provided by Spring Data (and JPA).
If your domain classes and your entity classes should be separate things depends on if they have different needs. You might encounter scenarios where you need to model entity classes to accommodate the limitations of JPA or whatever persistence technology you use and you don't want to leak that into you domain.
But until you encounter that I don't see the need to separate them.
If you are concerned about annotations on your entities, it might help to realise that annotations are an extremely weak dependency. You can use your entities without the annotations even on the class path. So from a purist point of view they are a smell, but in reality I still have to find a situation where they are problematic.
If you really want to get rid of them you might want to look into jMolecules, which offer technology agnostic annotations for DDD concepts that then get translated into JPA annotations or whatever you want to use.