Do JPA Entities Have To Be java.io.Serializable?
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!.
In addition, if you are implementing a clustered second level cache then your entities must be serializable or else you're going to have problems.
It's just easier to do so and making them serializable isn't an issues for boundaries since your interfaces set the boundaries, not the object itself implementing Serializable.
Posted by Mike Bosch on August 26, 2008 at 10:44 PM CEST #
Thanks for the explanation.
Posted by Prabhat Agarwal on December 02, 2015 at 02:08 PM CET #
Thanks, nice explanation
Posted by Binh Nguyen on June 21, 2017 at 06:09 AM CEST #