It is one of the classic FAQs: "Should I put business logic into JPA entities?" I guess the doubts originate from the old CMP 2.X days. Entity Beans were neither powerful, nor clean enough to be considered as domain object candidates. The dependency on the technology was heavy - on the other hand even inheritance wasn't supported. It was a common best practice to factor out the logic into the service layer. This led to procedural code - at least the business logic wasn't polluted with the technology...
With the advent of Hibernate and especially JPA, the weaknesses, and so the actual reasons, for the artificial separation of logic and state were basically eradicated. JPA entities are nothing but Java classes without any direct dependency on the particular technology (except of some runtime dependencies on weaved-in code), so there is no more reasons to keep them enemic. In fact I tend to answer the question with another question: "Why not? What can happen in worst case putting the logic into persistent entities?" There are some caveats doing so:
- If the entities are used as transfer objects as well, the client could invoke the methods what could change the whole graph. This could be hard to merge back.
- The logic of a domain object should really belong to it. Otherwise you could get lots of conditional code caused by the violation of seperation of concerns. There should be no client specific logic in the entities. Client-specific functionality should be factored out somewhere else...
On the other hand good domain objects are clean, concise and easy to test and maintain. There is no bloat caused by the artificial separation of state and behavior. On the other hand, actually nothing is transparent :-).
[This post was motivated by this off-topic comment :-) ]
Cloudy Jakarta EE and MicroProfile: Microservices, Clouds and Beyond Jakarta EE / MicroProfile airhacks workshops at MUC airport, Winter Edition
airhacks.fm the podcast:
Stay in touch: airhacks.news.