使用 JPA 和 Rest API 进行 Java 序列化

标签 java jpa serialization

正如我们所知,java 中的序列化,引用自博客 here已使用

to convert the state of an object into a byte stream, which can be persisted into disk/file or sent over the network to any other running Java virtual machine.

  • REST API 案例:

现在考虑第二种情况,通过网络发送到另一个正在运行的 jvm ,如果我们考虑 Rest API 的示例,即“host:port/path/资源”。

通常我使用 Spring 的 @RequestMapping 将资源模型 pojo 类返回为 ResponseEntity。我没有在模型类中实现Serialized接口(interface),一切正常,我得到了json格式的API响应。

ModelX.java

public class ModelX {

    private int x = 2 ;
    private String xs = "stringx";

    // getters and setters

}

Controller 方法:

@RequestMapping(value = "/test",method=RequestMethod.POST)
public ResponseEntity<ModelX> getTestModel(@RequestBody ModelX mox){

    ModelX mx = new ModelX();
    mx.setX(mox.getX());
    mx.setXs(mox.getXs());

    return new ResponseEntity<ModelX>(mx, HttpStatus.OK) ;
}

是因为 Spring 框架 使用这些 RestAPI 注释使其在幕后可序列化吗?如果不是,那么在不使其可序列化的情况下,我们如何能够通过网络发送。

<小时/>
  • 持久化案例:

为了更多的考虑,即使在将对象持久化到数据库的情况下,我们也使用JPA中的@Entity,现在我测试了是否有任何的实例>@Entity 注释类 IS-A Serializable 或不。它给出错误

@Entity
class Car {

int id ;
String name ;

//getters and setters

}

测试方法 -

Car c = new Car();
System.out.println(c instanceof Serializable);

O/p - false

所以即使当我们尝试将这个对象的状态保存在数据库中时,ORM 也会在幕后进行某种序列化?

最佳答案

序列化是一个通用概念:

In computer science, in the context of data storage, serialization (or serialisation) is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later (possibly in a different computer environment).

Serialized 用于序列化的单个特定实现,它恰好内置于 JVM 中,称为“Java 序列化”。但是转换为 JSON,或者转换为数据库用于通信的任何协议(protocol)也是序列化;它们只是与可序列化无关。

are there any specific scenarios or applications (maybe if you are aware of )where sending bytestream is more beneficial

一方面,二进制格式比 JSON 更小,并且读/写速度更快。而且它们仍然可以跨平台。但为此,您通常会使用与 Java 序列化不同的二进制格式:例如Protocol BuffersThrift (或许多其他)。

so if the app that sends the data goes down , data will still be available for the other jvm . (won't happen in case of API)

这也适用于 JSON(或上面的 PB 或 Thrift)。

关于使用 JPA 和 Rest API 进行 Java 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57107596/

相关文章:

java - 使用Java代码使用process编译类

java - 从 jpa-hibernate ddl auto 运行 sql 脚本

c++ - 从哪里获得用于 C++ 序列化的神话般的 Microsoft msgtool

java - 序列化动态生成的类

java - 我正在编写代码,通过获取输入使用 java 中的字符串显示 friend 的姓名。但索引 0 没有获取条目

java - 将(BST 的)迭代层序遍历转换为递归实现

java - Java String.toCharArray 中包含空格

hibernate - 使用 CriteriaQuery 和 EntityManager(Hibernate) 进行查询

java - 配置hibernate暂时使用 "show-sql=false"

objective-c - Plist 序列化导致内存泄漏