I want to save my java object to postgresql column and i'm looking for a simple way to do so.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With