Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do POJO classes need to implement the Serializable interface?

Tags:

java

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")
like image 431
Thiru Avatar asked May 29 '14 09:05

Thiru


People also ask

Why do we need to implement Serializable interface?

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.

Should a POJO implements Serializable?

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.

What is serialization in POJO class?

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.

Why do we implement Serializable in spring boot?

We use it to verify that the saved and loaded objects have the same attributes, and thus are compatible on serialization.


1 Answers

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

like image 200
shazin Avatar answered Oct 25 '22 09:10

shazin