Java Object Serialization and Deserialization In MySQL Database

In my previous article, I showed how any java object can be serialized to a file system, and how to read the object once it has been written to the file.

In this article, I am providing you a working code that I wrote and tested which stores java object into the database. I tested this coder the mysql database. There is no reason why it should not work for other databases.

The following is a summary of what is covered in this example:

  • Query to create tables in database for the purpose of storing java objects.
  • Query to write java objects to the database
  • Query to read java objects from the database
  • Basic mechanism of connecting to the database from Java Application
  • How to write Java Object to the database using prepared statements
  • How to read the Java Objects from the database using prepared statements.
  • You will see that the objects will be stored in database in the form of BLOB data type.

The following is a working code fully compiled and tested. Make sure to change the database credentials, url and name to suit your environment.

package com.kushal.serialization
/**SQL to create MySQL Table For Object Storing**/

/*CREATE TABLE javaobjects (
 objectid INT AUTO_INCREMENT,
 object_name varchar(100),
 object_value BLOB,
 primary key (objectid));
 */

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ObjectSerializationToMySQL {
	static final String SQL_TO_WRITE_OBJECT = "INSERT INTO JAVAOBJECTS(OBJECT_NAME, OBJECT_VALUE) VALUES (?, ?)";
	static final String SQL_TO_READ_OBJECT = "SELECT OBJECT_VALUE FROM JAVAOBJECTS WHERE OBJECTID = ?";

	static String driver = "com.mysql.jdbc.Driver";
	static String url = "jdbc:mysql://localhost/generaldb";
	static String username = "root";
	static String password = "root";

	/**
	 * This class will create and return a database connection.
	 */
	public static Connection getConnection() throws Exception {
		Class.forName(driver);
		Connection conn = DriverManager.getConnection(url, username, password);
		return conn;
	}

	/**
	 * This method will write a java object
	 * to the database
	 * Parameters: connection object and object to be serialized
	 */
	public static long writeJavaObject(Connection conn, Object object)
			throws Exception {
		String className = object.getClass().getName();
		PreparedStatement pstmt = conn.prepareStatement(SQL_TO_WRITE_OBJECT);
		pstmt.setString(1, className);
		pstmt.setObject(2, object);
		pstmt.executeUpdate();
		ResultSet rs = pstmt.getGeneratedKeys();
		int id = -1;
		if (rs.next()) {
			id = rs.getInt(1);
		}
		rs.close();
		pstmt.close();
		System.out.println("Serialization Successful."+
						   "Serialized Class: "+ className);
		return id;
	}

	/**
	 * This class will de-serialize a java object from the database
	 */
	public static Object readJavaObject(Connection conn, long id)
			throws Exception {
		PreparedStatement pstmt = conn.prepareStatement(SQL_TO_READ_OBJECT);
		pstmt.setLong(1, id);
		ResultSet rs = pstmt.executeQuery();
		rs.next();
		byte[] buf = rs.getBytes("object_value");
		ObjectInputStream objectIn = null;
		if (buf != null)
			objectIn = new ObjectInputStream(new ByteArrayInputStream(buf));
		Object object = objectIn.readObject();
		String className = object.getClass().getName();
		rs.close();
		pstmt.close();
		System.out.println("Deserialization Successful."+
							"nDeserialized Class: "+ className);
		return object;
	}

	/**
	 * Testing the serialization and deserialization feature.
	 */

	public static void main(String args[]) throws Exception {
		Connection conn = null;
		try {
			/**Creating DB Connection**/
			conn = getConnection();
			conn.setAutoCommit(false);
			/**Creating Test object to Serialize**/
			MyObjectToSerialize obj = new MyObjectToSerialize("Roberto",
					"Armando", 35);
			/**
			 * Serializing the object and getting the database id,
			 * which is nothing but an autogenerated key
			 */
			long objectID = writeJavaObject(conn, obj);
			conn.commit();
			System.out.println("Serialized object ID" + objectID);
			/**
			 * Reading the object from database.
			 * This object is just serialized into database above.
			 */

			MyObjectToSerialize objFromDatabase = (MyObjectToSerialize) readJavaObject(
					conn, objectID);
			System.out.println("After Deserialization:");
			System.out.println("Object Value: " + objFromDatabase);
			System.out.println("Class: " + objFromDatabase.getClass().getName());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			/**Closing the database connection**/
			conn.close();
		}
	}
}

The following is the class which is serialized/de-serialized using the class above. Please note that any class which has to be serialized needs to implement Serialization interface.  Please refer to my previous article for further details

package com.kushal.serialization;
/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified 09/01/2009 mm-dd-yyyy
 */
import java.io.Serializable;
public class MyObjectToSerialize implements Serializable {

	private String firstName;
	private String lastName;
	private int age;
	public MyObjectToSerialize(String firstName, String lastName, int age) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
	}
	public String toString() {
		return firstName + " " + lastName + ", " + age;
	}
}

===========
Output of this program:
Serialization Successful.Serialized Class: com.kushal.serialization.MyObjectToSerialize
Serialized object ID6
Deserialization Successful.
Deserialized Class: com.kushal.serialization.MyObjectToSerialize
After Deserialization:
Object Value: Roberto Armando, 35
Class: com.kushal.serialization.MyObjectToSerialize


Content of the database after running the program:

Serialzing A Java Object Into XML and De-Serialzing using XMLEncoder And XMLDecoder

This is my third post related to Java Object Serialization.

In the first post, I talked about serializing a Java Object to a binary file system.

I dealt with serializing the object to MySQL database in my second post.

In this post, I am providing you a working code on how to write (serialize) a java object into XML file using java.beans.XMLEncoder and reading the XML File into Java Object using java.beans.XMLDecoder

The XMLDecoder class is used to read XML documents created using the XMLEncoder and is used just like the ObjectInputStream. For example, one can use the following fragment to read the first object defined in an XML document written by the XMLEncoder class.

The XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean in the same way that the ObjectOutputStream can be used to create binary representation of Serializable objects. Despite the similarity of their APIs, the XMLEncoder class is exclusively designed for the purpose of archiving graphs of JavaBeans as textual representations of their public properties. Like Java source files, documents written this way have a natural immunity to changes in the implementations of the classes involved. The ObjectOutputStream continues to be recommended for interprocess communication and general purpose serialization.

package com.kushal.serialization;

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 10th September 2009
 *
 * Serializing Object To XML
 * Deserializing Object From XML
 */

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ObjectSerializationToXML {

	/**
	 * This method saves (serializes) any java bean object into xml file
	 */
	public void serializeObjectToXML(String xmlFileLocation,
			Object objectToSerialize) throws Exception {
		FileOutputStream os = new FileOutputStream(xmlFileLocation);
		XMLEncoder encoder = new XMLEncoder(os);
		encoder.writeObject(objectToSerialize);
		encoder.close();
	}

	/**
	 * Reads Java Bean Object From XML File
	 */
	public Object deserializeXMLToObject(String xmlFileLocation)
			throws Exception {
		FileInputStream os = new FileInputStream(xmlFileLocation);
		XMLDecoder decoder = new XMLDecoder(os);
		Object deSerializedObject = decoder.readObject();
		decoder.close();

		return deSerializedObject;
	}

	/**
	 * Testing.
	 * 1. Creates and Object.
	 * 2. Serializes Object To XML
	 * 3. Deserializes Object From XML
	 * 4. Prints The values hold in Object
	 */
	public static void main(String args[]) throws Exception {

		/* Location of XML File */
		String XMLLocation = "C:/myXMLFile.xml";

		ObjectSerializationToXML serializer = new ObjectSerializationToXML();

		/* Creating and filling a bean object */
		MyBeanToSerialize obj = new MyBeanToSerialize();
		obj.setFirstName("Johnny");
		obj.setLastName("Depp");
		obj.setAge(45);

		/* Serialzing Object to XML */
		System.out.println("Starting Serialization...");
		serializer.serializeObjectToXML(XMLLocation, obj);
		System.out.println("Serialized Object: " + obj.getClass().getName());
		System.out.println("Destination XML: " + XMLLocation);

		/* Reading the object from serialized XML */
		System.out.println("nnStarting De-Serialization...");
		System.out.println("Source XML: " + XMLLocation);
		MyBeanToSerialize deserializedObj = (MyBeanToSerialize) serializer
				.deserializeXMLToObject(XMLLocation);
		System.out.println("De-serialized Object: "
				+ deserializedObj.getClass().getName());
		System.out.println("nChecking For Values In De-Serialized Object");
		System.out.println("...First Name: " + deserializedObj.getFirstName());
		System.out.println("...Last Name: " + deserializedObj.getLastName());
		System.out.println("...Age: " + deserializedObj.getAge());

	}

}

The following is the java bean that will be serialized / deserialized.

package com.kushal.serialization;
/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 10th September 2009
 *
 * Simple Java Bean
 */
public class MyBeanToSerialize {
	private String firstName;
	private String lastName;
	private int age;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

}

================================
Output of running the file ObjectSerializationToXML
Starting Serialization…
Serialized Object: com.kushal.serialization.MyBeanToSerialize
Destination XML: C:/myXMLFile.xml

Starting De-Serialization…
Source XML: C:/myXMLFile.xml
De-serialized Object: com.kushal.serialization.MyBeanToSerialize

Checking For Values In De-Serialized Object
…First Name: Johnny
…Last Name: Depp
…Age: 45

The content of the generated XML File: