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 (
 object_name varchar(100),
 object_value BLOB,
 primary key (objectid));

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 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 {
		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);
		ResultSet rs = pstmt.getGeneratedKeys();
		int id = -1;
		if ( {
			id = rs.getInt(1);
		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();;
		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();
		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();
			/**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);
			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) {
		} finally {
			/**Closing the database connection**/

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
 * Last Modified 09/01/2009 mm-dd-yyyy
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:

[My Video Promotion]
  1. How to serialize Java objects into JSON format using Google’s GSON
  2. Java Object Serialization and Deserialization In MySQL Database
  3. How To Set Conditional Debug Breakpoints in Eclipse or IBM RAD?
  4. Rotating An Image In Java Graphics 2D By Specified Degree
  5. Java – How To Overlay One Image Over Another Using Graphics2D [Tutorial]
  6. Quick SQL Reference – Find Duplicate Data In A Table Using Having Clause
  7. Splitting PDF File Using Java iText API Into Multiple PDFs
  8. Object Serialization And De-Serialization In Java To Filesystem
  9. Finding Java Image Pixels Information – ARGB (Alpha, Red, Green Blue)
  10. Creating A 3D Pie Chart In Java Using JFreeChart [Example Source Code]
  11. Java Tutorial – Swing Text Drag And Drop – Sample Example
  12. Serialzing A Java Object Into XML and De-Serialzing using XMLEncoder And XMLDecoder
  13. Six Stages Of Debugging in Software Engineering
  14. Java 2D Graphics Example Tutorial On Paint, Gradient and Stroke
  15. Complete Tutorial On Using SOAP-UI to Mock Web Service Request / Response
  16. Listing The Content Of Zip File With Zip Information In Java
  17. Joke – Why do Java Programmers wear glasses?
  18. How to receive files via bluetooth in your MacBook Pro
  19. Calculating Folder Size Graphically and Generating Directory Size Chart In Java
Tagged , , , , , , , . Bookmark the permalink.

6 Responses to Calculating Folder Size Graphically and Generating Directory Size Chart In Java

  1. nocdib says:

    Thank you for this! It is just what I need

  2. d says:

    would that help you tocreate the file from ubunt server

  3. komal gaikwad says:

    in this code i got problem of array out of bound plz tell me solution.

  4. komal gaikwad says:

    In this code i got error
    Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 1
    plz send me proper code….

  5. Neethu says:

    Thank you very much for the solution. This is the one which i was searching.

  6. Manikant says:

    I need to copy to the shared folder which is shared and can be authenticate by using credentials.

    but here the code is giving to write .

    I need copy my folder from my local to shared location

    Please help

Leave a Reply to d Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.