If we just talk about persistence, Serializable
is not needed But it is best practice to make the entities Serializable
.
If we are exposing domain
/entities
objects directly exposed to the presentation layer, instead of using DTO
, In that case we need to implement Serializable
. These domain objects can be 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.
Composite identifiers
The primary key class must be serializable.
POJO Models
If an entity instance is to be used remotely as a detached object, the entity class must implement the Serializable
interface.
Cache
In addition, if you are implementing a clustered
second level cache
then your entities must be serializable
. The identifier has to be Serializable
because that’s a JPA requirement since the identifier
might be use as the key for a second-level cache entry.
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.