It's a kind of unwritten wisdom to mark all JPA-entities as java.io.Serializable. This is fine, but absolutely not required by the specification. You can implement Serializable but you don't have to. Actually under some conditions implementing java.io.Serializable would be an anti-pattern. In a SOA-like environment the visible service layer boundary have to be decoupled from the the domain or persistence layer. In such a case you will probably use dedicated Data Transfer Objects to decouple the service boundary from the internal realization. In that particular case marking the domain objects as Serializable (=JPA-Entities) would be counter-productive and would violate the "encapsulation".
On the other hand, in more pragmatic architectures, the domain objects could be exposed directly to the presentation layer. So instead copying the data from domain objects into DTOs, which is not DRY, you could just pass the detached JPA-entities as value holders to the web application or even rich clients. In both cases it is better to implement java.io.Serializable because:
- The implementation of java.io.Serializable is simply required for transfering data via IIOP or JRMP (RMI) between JVM-instances.
- In case of a pure web application the domain objects are sometimes stored in HTTPSession for caching / optimization purposes. A http-session can be serialized (passivation) or clustered. In both cases all the content have to be Serializable.
Thanks to Jacek Laskowski for the idea for the post!.
Web Apps, SPA, PWA with vanilla Java Script (ES 6+), CSS 3 and WebStandards only. As simple as possible, but not simpler. See you at: (Progressive) Web apps, Single Page Apps and WebStandards airhacks workshops at MUC airport, Winter Edition
airhacks.fm the podcast:
Stay in touch: airhacks.news.