5

I noticed in Spring-boot a lot of people create models/entities and implement the Serialiazable interface.

public class ModelBase implements Serializable 

I understand what it means to serialize data/classes as it enables you to save the state of a class (if I'm not wrong, to a file for instance).

But I believe this should be done only when necessary, but either way it seems people just tend to implement the interface.

Is there a different reason?

Ayo K
  • 1,719
  • 2
  • 22
  • 34
  • 4
    Its a requirement for a [JavaBean](https://en.m.wikipedia.org/wiki/JavaBeans) – Vince Feb 19 '18 at 16:00
  • 1
    One common reason to want to enable serialization is for sessions in an application server. For Tomcat/another application server to be able to store or unload a session from memory (passivate the session), any model objects or Spring beans at a session level will need to be Serializable. – df778899 Feb 19 '18 at 17:51
  • 1
    May [this](https://stackoverflow.com/a/2021640/6296931) help you. – Coder ACJHP Feb 19 '18 at 21:57
  • There are still many frameworks (eg. Java EE and Spring application servers) and specifications (JavaBeans) which require that authored classes use the JVM serialization facility. JVM serialization is likely to be less emphasized going forward due to the several security concerns it entails. – scottb Feb 20 '18 at 06:02

1 Answers1

3

When your models or entities are meant to travel across several JVM's then you might want to consider implementing Serializable interface. You should do this with caution. You should also provide a a valid UUID for the class to be used during Serialization and vice versa.

Sample is

private static final long serialVersionUID = 9178661439383356177L;

And

According to JPA Spec:

If 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.

Also

When using serializable values it is possible to remove this redundancy by changing the entity class in two ways:

Make the entity class serializable, so it can be used in place of the value class.

Make the key fields transient, so they are not redundantly stored in the record.

https://docs.oracle.com/cd/E17277_02/html/collections/tutorial/SerializableEntity.html

Knight Rider
  • 972
  • 2
  • 10
  • 22