Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving java object to PostgreSQL

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

  1. what type for columns stores objects ?
  2. I heard about serialization but i'm kind of lost. How can i serialize/deserialize object ?
like image 637
Mooh Avatar asked Feb 26 '23 17:02

Mooh


1 Answers

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 Serializable like so:

public YourClass implements Serializable {
    // ...
}

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

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.

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.

like image 50
BalusC Avatar answered Mar 05 '23 15:03

BalusC