Reputation: 2748
I'm writing an application which needs to write an object into database.
For simplicity, I want to serialize the object.
But ObjectOuputStream needed for the same purpose has only one constructor which takes any subclass of OutputStream as parameter.
What parameter should be passed to it?
Upvotes: 6
Views: 11516
Reputation: 597006
You can pass a ByteArrayOutputStream
and then store the resulting stream.toByteArray()
in the database as blob.
Make sure you specify a serialVersionUID
for the class, because otherwise you'll have hard time when you add/remove a field.
Also consider the xml version for object serialization - XMLEncoder
, if you need a bit more human-readable data.
And ultimately, you may want to translate your object model to the relational model via an ORM framework. JPA (Hibernate/EclipseLink/OpenJPA) provide object-relational mapping so that you work with objects, but their fields and relations are persisted in a RDBMS.
Upvotes: 8
Reputation: 53674
One thing to add to this. java serialization is a good, general use tool. however, it can be a bit verbose. you might want to try gzipping the serialized data. you can do this by putting a GZIP stream between the object stream and the byte stream. this will use a small amount of extra cpu, but that is often a worthy tradeoff to shipping the extra bytes over the network and shoving them in a db.
Upvotes: 2
Reputation: 552
e.g. create ByteArrayOutputStream and pass it to ObjectOuputStream constructor
Upvotes: 2
Reputation: 147124
Using ByteArrayOutputStream
should be a simple enough way to convert to a byte[]
(call toByteArray
after you've flushed). Alternatively there is Blob.setBinaryStream
(which actually returns an OutputStream
).
You might also want to reconsider using the database as a database...
Upvotes: 4