Why do POJO Java classes have to implement the Serializable
interface? What will happen if I do not implement Serializable
?
@Entity
@Table(name="Customer")
public class Customer implements Serializable {
private static final long serialVersionUID = -5294188737237640015L;
/**
* Holds Customer id of the customer
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "cust_id")
private int Custid;
/** Holds first Name of the customer*/
@Column(name = "first_name")
private String firstName;
/** Holds last Name of the customer */
@Column(name = "last_name")
private String lastName;
/** Holds Customer mobile number of customer*/
@Column(name = "cust_mobile")
private long MobileNo;
/**Holds customer address of customer*/
@Column(name = "cust_address")
Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so that the objects of these classes may get a certain capability. The Cloneable and Remote are also marker interfaces. The Serializable interface must be implemented by the class whose object needs to be persisted.
The POJO class can be used to implement serializable interfaces. The Java Beans must implement serializable interfaces. The POJO class fields can be accessed with their names. The Java Beans fields can be accessed only with the help of getters and setters.
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object.
We use it to verify that the saved and loaded objects have the same attributes, and thus are compatible on serialization.
First this is no longer a Plain Old Java Object, Because it has annotations.
But staying on your premise, The Serializable is required in POJOs if those are intended to be used in Distributed Systems and Systems which use caching and flushing into files and reading back.
Mostly JPA implementations do run in Distributed manner and Use caching, thus this POJO is required to implement Serializable.
For more information read this discussion
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With