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.
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:
Before you run the following example, you need to create a database and a table in it.
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.
- Stream the object to a ByteArrayOutputStream via an ObjectOutputStream.
- Convert the ByteArrayOutputStream to a byte array.
- Call the setBytes method on the prepared statement.
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:
- Read the byte array and put it into a ByteArrayInputStream
- Pass that to an ObjectInputStream
- Then read the object.
Before you run the following example, you need to create a database and a table in it.
0 comments:
Post a Comment