java - 序列化:基本理解和文档

标签 java hibernate serialization

Within a stream, the first reference to any object results in the object being serialized or externalized and the assignment of a handle for that object. Subsequent references to that object are encoded as the handle. Using object handles preserves sharing and circular references that occur naturally in object graphs. Subsequent references to an object use only the handle allowing a very compact representation.

Except for serializable fields, primitive data is written to the stream in block-data records, with each record prefixed by a marker and an indication of the number of bytes in the record.

  1. 以上内容来自 Oracle 序列化文档。我正在阅读序列化以获得更好、更深入的理解,有人可以帮我用简单的英语解码突出显示的部分吗? (我正在寻找有关如何生成流的上下文的答案,尤其是当它谈论原始数据如何存储在缓冲区中时)

Serialization is useful when we want to:

  • Persist the state beyond the lifecycle of the JVM - file/db
  • Send data over to another jvm based application over a network - data exchange

文档:https://docs.oracle.com/javase/6/docs/platform/serialization/spec/serial-arch.html

  • 我一直在使用 Spring/Hibernate,并且在任何应用程序中,模型都被定义为 Serialized 类型。使用 Serialized 的主要原因是为了将来增强的版本控制,但是如果没有 Serialized,Hibernate 会将数据保留在 DB 中/但使用 ObjectOutputStream 序列化到文件会失败。有人可以帮助我理解这一点,为什么 Hibernate 不要求实体是可序列化类型的?
  • 最佳答案

    只是我的理解 对于 #1 序列化后的对象流基本上包括 5 个部分:

    • 声明这是序列化文件的 header 以及序列化的版本。
    • 类的信息,如名称、序列化id(serialVersionUID)、字段数量等
    • 字段说明
    • 父类信息
    • 字段的值。

    从 ObjectOutputStream 检查这些代码:

    if (obj instanceof String) {
        writeString((String) obj, unshared);
    } else if (cl.isArray()) {
        writeArray(obj, desc, unshared);
    } else if (obj instanceof Enum) {
        writeEnum((Enum<?>) obj, desc, unshared);
    } else if (obj instanceof Serializable) {
        writeOrdinaryObject(obj, desc, unshared);
    } else {
    if (extendedDebugInfo) {
        throw new NotSerializableException(
        cl.getName() + "\n" + debugInfoStack.toString());
    } else {
        throw new NotSerializableException(cl.getName());
    }
    

    对于#2,我认为 hibernate/jpa 只是通过查询将它们写入数据库,它们不需要序列化对象。如果您需要传输然后跨 JVM 或其他用途,您可以使用 Serialized 实现实体(我认为您最好在基于 Web 的应用程序中进行序列化)。

    关于java - 序列化:基本理解和文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61652221/

    相关文章:

    mysql - 使用Mysql 5.7使用NULL IS NULL OR条件语法进行慢速查询

    c++ - 定义行为类似于标准 C++ 数据类型的新数据类型

    java - Android Java 使用 switch/case 来计算不同的百分比

    javascript - 正则表达式可选捕获未按预期工作

    java - 如何从另一个类访问和更改 JTextArea

    java - 仅在 java 序列化时重命名字段

    java - 如何序列化 float 组的ArrayList

    java - 在哪里可以找到 Java 标准库类的单元测试?

    java - 表单和实体类的用法

    java - Jpa与具有额外列的同一实体的多对多关系