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.


Run the following query to create a table before running the sample java program.
I used mysql and driver mysql-connector-java-5.0.3-bin.jar. You may use the database of your choice with tweaks to the connection strings.

[sql]
create database javaserialization;

CREATE TABLE `serialized_java_objects` (
`serialized_id` int(11) NOT NULL auto_increment,
`object_name` varchar(20) default NULL,
`serialized_object` blob,
PRIMARY KEY (`serialized_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

[/sql]

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

public class SerializeToDatabase {

	private static final String SQL_SERIALIZE_OBJECT = "INSERT INTO serialized_java_objects(object_name, serialized_object) VALUES (?, ?)";
	private static final String SQL_DESERIALIZE_OBJECT = "SELECT serialized_object FROM serialized_java_objects WHERE serialized_id = ?";

	public static long serializeJavaObjectToDB(Connection connection,
			Object objectToSerialize) throws SQLException {

		PreparedStatement pstmt = connection
				.prepareStatement(SQL_SERIALIZE_OBJECT);

		// just setting the class name
		pstmt.setString(1, objectToSerialize.getClass().getName());
		pstmt.setObject(2, objectToSerialize);
		pstmt.executeUpdate();
		ResultSet rs = pstmt.getGeneratedKeys();
		int serialized_id = -1;
		if (rs.next()) {
			serialized_id = rs.getInt(1);
		}
		rs.close();
		pstmt.close();
		System.out.println("Java object serialized to database. Object: "
				+ objectToSerialize);
		return serialized_id;
	}

	/**
	 * To de-serialize a java object from database
	 *
	 * @throws SQLException
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static Object deSerializeJavaObjectFromDB(Connection connection,
			long serialized_id) throws SQLException, IOException,
			ClassNotFoundException {
		PreparedStatement pstmt = connection
				.prepareStatement(SQL_DESERIALIZE_OBJECT);
		pstmt.setLong(1, serialized_id);
		ResultSet rs = pstmt.executeQuery();
		rs.next();

		// Object object = rs.getObject(1);

		byte[] buf = rs.getBytes(1);
		ObjectInputStream objectIn = null;
		if (buf != null)
			objectIn = new ObjectInputStream(new ByteArrayInputStream(buf));

		Object deSerializedObject = objectIn.readObject();

		rs.close();
		pstmt.close();

		System.out.println("Java object de-serialized from database. Object: "
				+ deSerializedObject + " Classname: "
				+ deSerializedObject.getClass().getName());
		return deSerializedObject;
	}

	/**
	 * Serialization and de-serialization of java object from mysql
	 *
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 * @throws IOException
	 */
	public static void main(String args[]) throws ClassNotFoundException,
			SQLException, IOException {
		Connection connection = null;

		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost/javaserialization";
		String username = "root";
		String password = "admin";
		Class.forName(driver);
		connection = DriverManager.getConnection(url, username, password);

		// a sample java object to serialize
		Vector obj = new Vector();
		obj.add("java");
		obj.add("papers");

		// serializing java object to mysql database
		long serialized_id = serializeJavaObjectToDB(connection, obj);

		// de-serializing java object from mysql database
		Vector objFromDatabase = (Vector) deSerializeJavaObjectFromDB(
				connection, serialized_id);

		connection.close();
	}
}

Output of the above java program

Java object serialized to database. Object: [java 1="papers" language=","][/java]
Java object de-serialized from database. Object: [java 1="papers" language=","][/java] Classname: java.util.Vector

This Core Java tutorial was added on 09/01/2010.

Comments on "Serialize / De-Serialize Java Object From Database" Tutorial:

  1. Vinit says:

    you are contradicting view on java serialization in this post compared to last post. In last post, you have mentioned that java serialization is not about storing object state in database and here you are providing example!

  2. Joe says:

    Vinit,
    In my previous post for serialization, I mentioned that, “don’t use java serialization as a replacement for database”. As, “This is not the primary purpose of java serialization”.

    To serialize you can use database as a medium, but I say “don’t use serialization as instead of database”.

  3. Eliza sahoo says:

    Good one .I was looking for the answer since some days.thanks it helped me a lot.

  4. Tousif Khan says:

    Hi,
    A good post like this is always appreciable. Thanks for the post. But people are looking for XML and CSV as the object data stores. For persisting in databases, we have other tools( like ORM’s ) are available. Any way. a nice Post :D.

  5. Usman says:

    Nicely explained.
    Thanks

  6. mohan says:

    nice example but i want to store some employee type object how can i store?

  7. Yousuf Zaman says:

    I have a complex object which contain a huge tree, to building this tree it make a huge pressure on database and tree building process happens regularly.
    So, in this case is this good practice – if i try to implement the tree like bellow ?
    i know when the tree data will change to database, so when the tree database[related tables for tree building] is changed , then i will build the tree object from related tables and put/save the tree object to database using serialization. so that no need to create tree object for all tree building request, only need to retrieve the object from database.

    Is this will be a good practice or decision? can u please reply?

  8. William Callahan says:

    I cannot thank you enough! This was the biggest help for my Senior Project. Without this page, I would not have completed my project. Although I didn’t follow your exact code, without a few statement I found here, I would be screwed. Thank You so much.

  9. dinesh says:

    It has been very helpful for me and I learnt a lot from this post and I really appreciate it.thanks,

  10. Saurav says:

    When I’m persisting objects in database through hibernate or JPA, do the objects always has to be serializable? Is it possible to persist objects that have not implemented the serializable interface through hibernate or JPA?

  11. Krishna says:

    It is very helpful to me, thanks a lot.

  12. ravi says:

    hello sir i’ve tried the code to store an object into database in oracle but it was throwing the error

    Exception in thread “main” java.io.StreamCorruptedException: invalid stream header: 00540001
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:801)
    at java.io.ObjectInputStream.(ObjectInputStream.java:298)
    at org.project.DbPractie.ObjectTest.main(ObjectTest.java:91)

    can u please tell me the reason and how to overcome that..

  13. Cory H says:

    Thanks for the article Joe; it helped me a great deal. :)

  14. Anonymous says:

    Hi Sir,

    I am also getting the similar Exception(java.io.StreamCorruptedException) as mentioned in above comment.
    Any suggestions please?

  15. Anonymous says:

    I’m getting java.sql.SQLException: Invalid column type,
    even I’m using blob

  16. RukminiKrishna says:

    I was trying to execute this program using SQL Server 2010 as storage for the objects. I am ending up with following error.

    Exception in thread “main” com.microsoft.sqlserver.jdbc.SQLServerException: The conversion from UNKNOWN to UNKNOWN is unsupported.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
    at com.microsoft.sqlserver.jdbc.DataTypes.throwConversionError(DataTypes.java:1117)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setObject(SQLServerPreparedStatement.java:991)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setObjectNoType(SQLServerPreparedStatement.java:926)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setObject(SQLServerPreparedStatement.java:935)
    at SerializeToDatabase.serializeJavaObjectToDB(SerializeToDatabase.java:60)
    at SerializeToDatabase.main(SerializeToDatabase.java:148)

    My OS in Win7. also, after changing the code.. i get stream header error.

    Any help would be appreciated

  17. RukminiKrishna says:

    I get the same error.. Any help?

  18. Hari says:

    Works fine in Db2 v9.7.Thanks

  19. Albino Python says:

    Really great post. Helped me out tremendously.

  20. ravi says:

    Nice Artilca;…

  21. Vijay Aneraye says:

    change the oracle version, may be use the older version could solve your problem.. I had the same problem and resolved by using the older version of ojdbc or oracle driver jar

Comments are closed for this "Serialize / De-Serialize Java Object From Database" tutorial.