Serialize / De-Serialize Java Object From Database

In recent days generalization have become popular in software development. You build a common platform and generate applications out of it to reduce the cost. In such applications an activity that will be frequently performed is serializing java objects to database.
There are many fancy tools and framework available to do this. Before using all of those, you need to understand the low level details of serializing a java object to database.

In older days before the advent of JDBC 3.0 you need to completely rely on streams.
  1. Stream the object to a ByteArrayOutputStream via an ObjectOutputStream.
  2. Convert the ByteArrayOutputStream to a byte array.
  3. Call the setBytes method on the prepared statement.
Now you can use Object type support from jdbc to store the object into database.
There are some key factors before performing serialization.
1. Database in use
2. Datatype to be used to persist the object
Also know some fundamentals of serialization.
I have given a sample java source code below to serialize and de-serialize java object to mysql database. In that, I have commented a line
Object object = rs.getObject(1);
Enable this line and comment the following 4 lines and execute and see the result. You will learn one more point.
To de-serialize a java object from database:
  1. Read the byte array and put it into a ByteArrayInputStream
  2. Pass that to an ObjectInputStream
  3. Then read the object.
Sample Java Source Code – Serialize to DB
Before you run the following example, you need to create a database and a table in it.

0 comments:

Post a Comment