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:

  1. The implementation of java.io.Serializable is simply required for transfering data via IIOP or JRMP (RMI) between JVM-instances.
  2. 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.
The Netbeans 6.5 bevavior covers well the 80% cases. However I remove in some cases the generated implementation of  java.io.Serializable afterwards.

Thanks to Jacek Laskowski for the idea for the post!.


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 8, Java 9: Bootstrap, Effective, Architectures, Single Page Apps, Progressive Web Apps, HTML 5, ES 6, CSS 3 and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

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 #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License