7

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 ?

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This link, java2s.com/Code/Java/Database-SQL-JDBC/… has put it very easily, that is without using any ByteArrayInputStream, ObjectOutputStream, etc classes. Can you please tell me if there is a problem with that ?
I've come across this answer seeking to do similar, and it seems for some reason my compiler takes issue with: preparedStatement.setBinaryStream(bais); It cannot resolve the method. I've read into the docs, and it seems like the parameter agrees with the specification, so I'm not sure what the problem is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.