Java 为什么 POJO 类需要实现 Serializable 接口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23930580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:09:23  来源:igfitidea点击:

Why do POJO classes need to implement the Serializable interface?

java

提问by Thiru

Why do POJO Java classes have to implement the Serializableinterface? What will happen if I do not implement Serializable?

为什么 POJO Java 类必须实现Serializable接口?如果我不执行会发生什么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")

采纳答案by shazin

First this is no longer a Plain Old Java Object, Because it has annotations.

首先,这不再是一个普通的旧 Java 对象,因为它有注释。

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.

但是在您的前提下,如果 POJO 旨在用于分布式系统和使用缓存和刷新到文件中并回读的系统,则需要在 POJO 中使用 Serializable。

Mostly JPA implementations do run in Distributed manner and Use caching, thus this POJO is required to implement Serializable.

大多数 JPA 实现确实以分布式方式运行并使用缓存,因此需要此 POJO 来实现 Serializable。

For more information read this discussion

有关更多信息,请阅读此讨论

回答by Frank

The term "POJO" was invented to seperate between lightweight and heavyweight EJB concepts.

发明术语“POJO”是为了区分轻量级和重量级 EJB 概念。

POJOs do not require you to implement anything.

POJO 不需要你实现任何东西。

It was used for objects that must NOT implement heavyweight EJB interfaces.

它用于不能实现重量级 EJB 接口的对象。

The term became obsolete with the introduction of JEE5 and the subsequent use of lightweight annotations for the definition of EJBs.

随着 JEE5 的引入以及随后对 EJB 定义使用轻量级注释,该术语变得过时了。

From my expirience I would say that the term is now toxic and should not be used anymore. Nowadays it is just a common source of misunderstandings and unnecessary discussions.

根据我的经验,我会说这个词现在有毒,不应再使用。如今,它只是误解和不必要讨论的常见来源。

BTW: I believe you are referring to "JavaBeans".

顺便说一句:我相信您指的是“JavaBeans”。