Sunday, 18 August 2013

Serializing object to database

Serializing object to database

I know we can wrap FileOutputstream in ObjectoutputStream, FileInputStream
in ObjectInputStream and use ObjectOutputstream.writeObject and
ObjectInputstream.readobject() methods to serialize Java objects to a
file.
If instead of a file I want to serialize the object to a database then all
I would need to do is call setObject() method of PreparedStatement to
write the object and getObject() of ResultSet to retrieve the object.
If the class for the object we are attempting to serialize has not
implemented the Serializable interface then in case of serializing the
object to file we will get a NotSerializableException
However in case of serializing the object to DB since we are not at all
using writeObject but just using PreparedStatement setObject method,so the
JVM will throw any exception if class is not Serializable.
So does this mean that while serializing object to database it is not
necessary to implement Serializable interface?

No comments:

Post a Comment