Do JPA entities have to be Serializable

Just for the sake of persistence, Serializable is not needed (Not with Hibernate also). But it is best practice to make them Serializable.

According to JPA spec:

An entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface.

When domain objects are directly exposed to the presentation layer, instead of using DTO or VO (copying data from domain objects to DTO, violates DRY), we could just pass the detached entities as value holders to web application. In that case we need to implement Serializable. Because then the domain objects are sometimes stored in HTTPSession for caching/optimization purposes. A http-session can be serialized or clustered. And it is also required for transferring data between JVM-instances.

When we use DTO to decouple persistence layer and service layer, marking the domain objects as Serializable would be counter productive and would violate the “encapsulation”. Then it becomes an anti-pattern.

And when we serialize entities make sure to provide explicit serialVersionUID with private access modifier.  Because if a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in Java(TM) Object Serialization Specification . Default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Private access modifier is the convention because you do not want it in any subclass.