将 java 对象保存到 PostgreSQL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4295308/
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-09-20 00:25:06  来源:igfitidea点击:

Saving java object to PostgreSQL

javasqlpostgresqlserializationjdbc

提问by Mooh

I want to save my java object to postgresql column and i'm looking for a simple way to do so.

我想将我的 java 对象保存到 postgresql 列,我正在寻找一种简单的方法来做到这一点。

  1. what type for columns stores objects ?
  2. I heard about serialization but i'm kind of lost. How can i serialize/deserialize object ?
  1. 列存储对象的类型是什么?
  2. 我听说过序列化,但我有点迷茫。如何序列化/反序列化对象?

回答by BalusC

There's no specific column type. DB's like PostgreSQL doesn't understand Java. Serialization is indeed one of the ways. All you need to do is to let the class in question implement Serializablelike so:

没有特定的列类型。DB 就像 PostgreSQL 不理解 Java。序列化确实是其中一种方式。你需要做的就是让有问题的类Serializable像这样实现:

public YourClass implements Serializable {
    // ...
}

Then you'll be able to write it to an ObjectOutputStreamand read from an ObjectInputStream. You can then use PreparedStatement#setBinaryStream()to persist it to a binary column. In PostgreSQL, that's the byteatype.

然后,您将能够将其写入 anObjectOutputStream并从ObjectInputStream. 然后,您可以使用PreparedStatement#setBinaryStream()将其持久化到二进制列。在 PostgreSQL 中,这就是bytea类型。

YourClass instance = getItSomehow();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(instance);
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

Connection connection = null;
PreparedStatement preparedStatement = null;

try {
    connection = database.getConnection();
    preparedStatement = connection.prepareStatement(SOME_SQL);
    preparedStatement.setBinaryStream(bais);
    // ...

Needless to say that this is not the best practice. Rather map your object (javabean?) to a fullworthy table wherein each column represents a property of the object. E.g.

不用说,这不是最佳实践。而是将您的对象(javabean?)映射到一个完整的表,其中每一列代表对象的一个​​属性。例如

public class Person {
    private Long id;
    private String firstname;
    private String lastname;
    private Integer age;
    // ...
}

Which is then mapped against such a table:

然后将其映射到这样的表:

CREATE TABLE Person (
    id SERIAL PRIMARY KEY,
    firstname VARCHAR(255),
    lastname VARCHAR(255),
    age NUMERIC(3)
)

That's much more clear and better maintainable, reuseable and automatable.

这更清晰,更易于维护、可重用和可自动化。