I realize that persistence frameworks such as Morphia and Hibernate rely on annotations on domain objects to do their magic. At some level, it seems to me that this is insertin
Something found in DDD community
Post by Chris Richardson * If you want to keep JPA out of the domain model then use XML instead of annotations (i've never been a fan of ORM annotations since IMHO it mixes concerns)
Personally I like a lot to use annotations, XML was always for me error-prone, one small change in a field name and you need to manually change XML too. If you want to refactor a single class of your domain, you could end up changing several files instead of it being handled automatically. But lately, I'ven been reconsidering this because I want to be able to use several persistent options in a project. I do not want anything related to persistence in my domain, so XML is an option. Still, several times I get to a point where there is no direct mapping, or I still want to use annotations because they are so easy to change and visible right into the code. Somethinig I've been doing lately is create my business domain class as and abstract one, and user another for persistence extending it. Something like this:
public abstract class Persona {
private Setstates;
public boolean inState(State state){
return states.contains(state);
}
}
if, for some reason there is a db where states are already defined as a single column, and no direct mapping is possible, I can extend business class and used it as a persistence entity.
@Entity
public class PersonaSql extends Persona {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String statesDefinition;
@PrePersist
void prePersist(){
this.statesDefinition = mapStatesSetToString();
}
@PostPersist
void postPersists(){
this.states = mapStatesStringToSet();
}
}
Of course, this is a trivial example. There are other ways to solve this issue, my point is: by using inheritance you can take the great advantages of working with annotations and have your business model ignorant of specific persistence code.
Another option without using inheritance is converting persistence entity to business model and viceversa, but I won't recommend going this route (even with things like automapper), unless your domain is simple and you are sure it is going to stay simple. For example, if you are creating micro-services, your domain should be simple enough and its expected to be simple.