Object Persistence in Java

Introduction/*
At the time of development, sometimes it is necessary* Code to deserialize the object
to store the state of the object in the file system.*/
Some objects may or may not be stored in the fileObjectInputStream oin = new ObjectInputStream( new
system depending upon the structural intensity of theFileInputStream("D:/test.ser"));
object graph. In this article, I will focus on two majorEmp emp1 = ( Emp )oin.readObject();
aspects of the object persistence. Before going to thisSystem.out.println("Emp age----"+emp1.getAge());
subject, I would like to tell you about the significance ofSystem.out.println("Emp Name----"+emp1.getName());
the object persistence. Object persistence}catch( Exception e )
presupposes the state of the object in the file system.{e.printStackTrace();
In this matter you can make argument regarding}
object persistence in the database, which hibernate}
does. But so far this article is concerned I will give}
glimpse on persistence in the file system for allYou can run the above code in your editor to test the
convenience. The state of object signifies thefunctionalities relating to serialization.
attributes or properties of the object in the broaderNow I put forward some cases for seriliazation.
sense. The object graph represents the internalCase-1:
morphological structure of the object. So persistingIf your object does not implement Serializable interface,
object means, you are going to store all the internalIn order to serialize an object, it is a must that the class
changed structure of the object.must implement seriliazable interface. This is the
Technicalitiesrequired principle of serilization. Oterwise it will throw
There are several ways you can persist the state ofNotSerializationException.
the object. You can take help from Java IO system toThere is another way, if your class does not
store the object in the file system. However there areimplement Serilizable interface, you have to declare the
convenient approaches you can meet yourobject as transient. So that that object state will not be
expectations in this regard. One way is the textualpersisted.
representation of the object graph in the file systemCase-2:
and another way is the binary representation of theIn case of inheritance, your super class does not
object graph. These ways are very much convenientimplement Serializable interface and sub class also
and easy from the view point of development. Youdoes not.
can achieve the textual representation of the objectIn this case serilization will not happen . If you are
graph using XMLEncoder and you can achieve theinterested to store the all the properties of the object
binary representation of the object graph using javayou can go for XMLEncoder and XMLDecoder as I
object serialization process. Let me explain the twohave alredy explained you.
approaches below.Case-3:
Persistence using XMLEncoderIn case of inheritance, your class implements
XMLEncoder class is an approach to persist theSerializable interface and sub class does not.
object graph in an XML document or simply in an XMLIn this case, you should not worry about it, seriliazation
file. It provides the flexibility of storing the object as ahappens.
textual approach. In this approach you can see theCase-4:
XML file and you can easily understand the attributesIn case of inheritance, your super class does not
of the object. Similarly to obtain the object graph fromimplement Serializable interface but your sub class
the XML file, you can use XMLDecoder. All thesedoes.
classes have been defined in the java.beans package.Seriliazation will happen but with a lemon falvour. Here
Let me clarify all the aspects by citing the completeno exception will be thrown but your super class data
example.members or object properties of your super class will
Create a normal java bean or class having thebe not be persisted. When you deserialize object, you
following structure.will get the default values of your super class object.
Let us see the class called Emp.java which is a normalCase-5:
java bean.This is the best case. You super class and sub class
There is another test harness class calledimplement serializable interface.
TestPersistence.java which exposes the use ofEverything is fine here, serilization happens.
XMLEncoder and XMLDecoder.Case-6:
The following is the Emp.java.packageIf your object uses transient modifiers inside the
com.core.persist;objects,
/**You have to remember that transient objects or
* This is a simple java bean.variables will not be persisted in case of serialization.
* @author Debadatta Mishra(PIKU)Case-7:
*If your object uses volatile modifiers inside the object,
*/public class EmpThere is nothing to worry about, serialization will
{private String name = null;private int age = 0;privatehappen normally and data will be persisted.
String empId = null;public Emp()Case-8:
{super();If your object uses static modifiers inside the object,
}public String getName() {return name;You have to remember that,since static is not a part
}public void setName(String name) {this.name = name;of object, so static variables or static object reference
}public int getAge() {return age;will not be persisted in case of seriaization.
}public void setAge(int age) {this.age = age;Case-9:
}public String getEmpId() {return empId;It is a very special case I am going to focus on. You
}public void setEmpId(String empId) {this.empId = empId;may encounter the following situations at the time of
}serialization.
}• You are not sure whether your super class does
The following is the TestPersistence.javapackageimplement serializable interface.
com.core.persist;import java.beans.XMLDecoder;import• You do not have access to the source code of
java.beans.XMLEncoder;importyour super class.
java.io.BufferedInputStream;import• Your super class may be a final class.
java.io.BufferedOutputStream;import• Your super class may contain noe-serializable
java.io.FileInputStream;import java.io.FileOutputStream;object reference.
/**In this case, if you feel frustration and disappointment,
* This is a test harness class to display theyou can go for XMLEncoder and XMLDecoder as I
* use of XMLEncoder and XMLDecoder.have already explained.
* @author Debadatta Mishra(PIKU)If you want to persist the object using java’s
*serialization concept and mechanism, you have to do it
*/public class TestPersistencelittle bit intelligently and manually.
{public static void main(String[] args)Please refer to the following piece of code.
{The following class name is Emp.javapackage
Emp emp = newcom.core.persist;import java.io.ObjectInputStream;import
Id("A123");tryjava.io.ObjectOutputStream;import java.io.Serializable;
{/**
/** This is a simple java bean.
* The following codes are used to persist the Emp* @author Debadatta Mishra(PIKU)
object graph*
*/*/public class Emp implements Serializable
XMLEncoder encoder = new XMLEncoder(new{private static final long serialVersionUID =
BufferedOutputStream(new FileOutputStream("C:-164971138528601769L;private String name = null;private
oder.close();int age = 0;private String empId = null;private transient
/*Project proj = null;public Emp()
* The following codes are used to obtain the Emp{super();proj = new Project();
object graph}public String getName() {return name;
* from the XML document}public void setName(String name) {this.name = name;
*/}public int getAge() {return age;
XMLDecoder decoder = new XMLDecoder(new}public void setAge(int age) {this.age = age;
BufferedInputStream(new FileInputStream("C:}public String getEmpId() {return empId;
emp.xml")));}public void setEmpId(String empId) {this.empId = empId;
Emp emp1 = ( Emp}public Project getProj() {return proj;
)decoder.readObject();decoder.close();}public void setProj(Project proj) {this.proj = proj;
System.out.println("Emp Name=>"+emp1.getName());}
System.out.println("Emp Age=>"+emp1.getAge());/**You are proividing a default callback method
System.out.println("Emp Id=>"+emp1.getEmpId());* for manual seriallization process.
}catch( Exception e )* @param os of type {@link ObjectOutputStream}
{e.printStackTrace();* @throws Exception of type {@link Exception}
}*/private void writeObject( ObjectOutputStream os )
}throws Exception
}{try
The following is the output of the above example.{os.defaultWriteObject();os.writeInt(
If you run the above classes, an XML document calledproj.getProjectId());os.writeObject(
emp.xml will be created in the specified location. Theproj.getPojectName() );
xml document will look like the following.}catch( Exception e )
23{e.printStackTrace();
A123}
John}
So you have stored the state of the Emp object in the/**You are providing default desrialization with
xml document. It is also required to load the Emp* some manual twik.
object from the xml document. For this purpose you* @param oin of type {@link ObjectInputStream}
have use XMLDecoder which has been used in the* @throws Exception of type {@link Exception}
test harness class. If you want to test the above two*/private void readObject( ObjectInputStream oin )
classes, you can copy the classes and change thethrows Exception
package structure and you can run it. In case of{try
loading the object using XMLDecoder, it takes help{oin.defaultReadObject();proj = new
from java’s reflection system.e( (String) oin.readObject() );
Advantages of XMLEncoder and XMLDecoder}catch( Exception e )
• Since it is a textual representation of the object{e.printStackTrace();
graph, anybody can see the XML file and it helps in the}
portability to any other system.}
• If you want to change the value of a particular}
property of an object, you can do it directly in the XMLThe following class name is Project.javapackage
document so that while using XMLDecoder, you willcom.core.persist;
get your modified value./**
• If the object’s variables are declared transient,* @author Debadatta Mishra(PIKU)
still you are able to store the complete object graph*
along with the transient variable’s value. This case*/public class Project
is not possible in case of java object serialization.{private int projectId = 0;private String pojectName =
• It is also very easy and convenient in case ofnull;public Project()
object inheritance. There is no need to bother about{super();
the super class and sub class. Some of the limitations}public String getPojectName() {return pojectName;
of normal java object serialization can be over come}public void setPojectName(String pojectName)
in this approach.{this.pojectName = pojectName;
Persistence using Serialization}public int getProjectId() {return projectId;
Serialization is a java’s default mechanism to save}public void setProjectId(int projectId) {this.projectId =
the state of the object or simply the object graph inprojectId;
the file system. In this case your object will be}
persisted in the file system where the file is not human}
readable. It means that you are going to store theThe following class name is TestSerialization.java
binary representation of the object graph in the filewhich is test harness class.package
system. This object serialization can be achieved usingcom.core.persist;import java.io.FileInputStream;import
the writeObject() method of the classjava.io.FileOutputStream;import
ObjectOutputStream. The main thing you have tojava.io.ObjectInputStream;import
remember is that the object you are going to persistjava.io.ObjectOutputStream;
must implement Serialization interface which is called/**
as marker interface. In next article I will explain you the* @author Debadatta Mishra(PIKU)
use and the beauty of the marker interfaces. Similarly*
deserialization means retrieval of object from the*/public class TestSerialization
saved state. You can achieve the deserialization using{public static void main(String[] args)
readObject() method of the ObjectInputStream class.{
Please refer below the following piece of code toEmp emp = new
achive serialization.("John");
The following is class called Emp. It implementsProject proj = new
Serializable interface. There is another class calledZ");emp.setProj(proj);try
TestSerialization. This class performs both serilization{
and deserilization. This is the normal way of serilizationObjectOutputStream ous = new
concept from java.package com.core.persist;importObjectOutputStream(new FileOutputStream("D:
java.io.Serializable;test.ser"));ous.writeObject(emp);ous.close();
/**ObjectInputStream oin = new ObjectInputStream(new
* This is a simple java bean.FileInputStream(
* @author Debadatta Mishra(PIKU)"D:/test.ser"));
*Emp emp1 = ( Emp )oin.readObject();
*/public class Emp implements SerializableSystem.out.println("Emp age----"+emp1.getAge());
{private static final long serialVersionUID =Project proj1 = emp1.getProj();
-164971138528601769L;private String name = null;privateSystem.out.println("Proj Id-----"+proj1.getProjectId());
int age = 0;public Emp()System.out.println("Proj
{super();Name----"+proj1.getPojectName());
}public String getName() {return name;}catch( Exception e )
}public void setName(String name) {this.name = name;{e.printStackTrace();
}public int getAge() {return age;}
}public void setAge(int age) {this.age = age;}
}}
}Please see the two methods writeObject() and
Class TestSerialization.javapackagereadObject() inside the class Emp. These two
com.core.persist;import java.io.FileInputStream;importmethods are significant in the sense that you are going
java.io.FileOutputStream;importto achieve serialization with your default object as well
java.io.ObjectInputStream;importas manual serialization with the non serializable object
java.io.ObjectOutputStream;public classwith some data. When you call the methods
TestSerializationwriteObject() and readObject() for a particular object
{public static void main(String[] args)these methods will be invoked automatically and will
{persist some default data. In these particular methods
Emp emp = newyou are persisting data manually and thereby making
Emp();emp.setAge(23);emp.setName("John");trythe whole object serializable.
{Conclusion
/*I hope that you will enjoy my article. If you find any
* Code to serialize or persist the objectproblems or errors, please feel free to send me a mail
*/in the address . This article is only meant for those
ObjectOutputStream ous = new ObjectOutputStream(who are new to java development. This article does
new FileOutputStream("D:not bear any commercial significance. Please provide
test.ser"));ous.writeObject(emp);ous.close();me the feedback about this article.