Are persistence annotations in domain objects a bad practice?
annotations, domain-driven-design, hibernate, java, morphia
Solution
In my latest iteration on an existing system using Spring and Hibernate, I have started to move in a similar matter. When first implementing Hibernate models, I strove to separate the application logic in service classes from the persistence logic via data access objects. When building a new system last year I allowed most of the persistence objects to serve as the domain objects because that was the expedient solution.
However, I am redesigning this same system in light of changing business requirements, and I'm again leaning towards separating those concerns. I'm only a few days into the new design, but already I find myself preferring to have one object that represents the in-memory concerns object while a separate persistence-based object is used to store its state changes to the database. For example, I have a `Lead` for persistence and a parallel `ActiveLead` that lives across transactions.
I'm not yet convinced this is the best method, but it makes sense on a gut level. I've longed to have a collection of persistence-agnostic--nay, persistence-ignorant--set of objects that remain memory-resident across database transactions without regard to the standard CRUD simplifications. Yet I understand that in the end all database operations are implemented as CRUD. The two worlds must collide, and the trick is in making them dance in harmony.
Hibernate annotations on domain objects? This is a fine compromise between ease of implementation vs. ease of maintenance in my view.
Problem
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 inserting persistence concerns into the domain layer which is something we're supposed to strive to avoid. Is this something that I should try to dodge by perhaps using an external configuration file or maybe separate DTOs from the domain model? Or is this little leak between the persistence and domain layers generally regarded as acceptable?