Serilization /DeSerilization of Object Using Hibernate :
Or
Storing Java Object into the Database :
Step1:
Let Us consider a table with name Company ,
Company table consists of below columns
companyId Integer/number ,----Primary Key
companyName String ,
Location String/varhcar .
Consider another table with name Employee
Let us take below columns
empId Integer/Number,-----Primary Key
empName String/varchar2,
designation String/varchar2
Department String/varchar2
companyId Integer/number ----Foreignkey (Company table)
Created another table to store the Model Objects or java objects into the Database
Say fog eg ,
We want to delete the records from Company and Employee table permanently.
But we want to maintain or store these records for reporting purpose like to know the records say employee or company records deleted from the database
And this data should be useable by java application becaz we are generating reports using Java
For this I have created another table
PermanentlyDeletedData
logId Integer/number ----primary key,
ObjectNameOrTableName ---String/varhcar2
ObjectValueOrTableRow --- Blob(TO store the objects)
Step 2:
Once we have created above tables , just map these tables with corresponding model objects as like below in hbm files say for eg. Hibernate-config.hbm.xml or company.hbm.xml or mapping.hbm.xml
<hibernate-mapping>
<class name="com.ram.tri.serilization.Company" table="COMPANY">
<id name="companyId" column="companyId" type="integer">
<generator class="sequence">
<param name="sequence">COMPANY_SEQ</param>
</generator>
</id>
<property name="companyName" column="companyName" type="string"></property>
<property name="location" column="location" type="location"></property>
<set name="employesSet" lazy="false" inverse="false" cascade="all">
<key>
<column name="companyId" />
</key>
<one-to-many class="com com.ram.tri.serilization.Employee " />
</set>
</class>
<class name=" com.ram.tri.serilization.Employee " table="Employee">
<id name="empId" column="empId" type="integer">
<generator class="sequence">
<param name="sequence"> Employee _SEQ</param>
</generator>
</id>
<property name="empName" column="EMPNAME" type="string"></property>
<property name="designation" column="designation" type="string"></property>
<property name="department" column=”department"
type="string"></property>
<property name="companyId" column="companyId" type="integer"></property>
</class>
<class name=" com.ram.tri.serilization.PermanentlyDeletedData " table=" PermanentlyDeletedData ">
<id name="logId" column="LogId" type="integer">
<generator class="sequence">
<param name="sequence"> PermanentlyDeletedData _SEQ</param>
</generator>
</id>
<property name=" objectNameOrTableName " column=" ObjectNameOrTableName " type="string"></property>
<property name=" ObjectValueOrTablevalue " column=" objectNameOrTableName " ></property>
</class>
</hibernate-mapping>
Step 3:
Creating Model Objects :
Employee:
package com.ram.tri.serilization;
import java.io.Serializable;
/**
* TO Represents Emp table
*/
/**
* @author ram
*
*/
public class Employee implements Serializable {
private Integer empId;
private Integer companyId;
private String empName ;
private String designation ;
private String department ;
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public Integer getCompanyId() {
return companyId;
}
public void setCompanyId(Integer companyId) {
this.companyId = companyId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}
Company :
package com.ram.tri.serilization;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* TO Represents Company table
*/
/**
* @author ram
*
*/
public class Company implements Serializable{
private Integer companyId;
private String companyName ;
private String location ;
private Set<Employee> empSet = new HashSet<Employee>();
public Integer getCompanyId() {
return companyId;
}
public void setCompanyId(Integer companyId) {
this.companyId = companyId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Set<Employee> getEmpSet() {
return empSet;
}
public void setEmpSet(Set<Employee> empSet) {
this.empSet = empSet;
}
// To add one object at a time to set
public void addEmployee(Employee employee) {
empSet.add(employee);
}
}
PermenentlyDeletedData:
package com.ram.tri.serilization;
import java.io.Serializable;
/**
* To Store the deleted objects
*/
/**
* @author ram
*
*/
public class PermanentlyDeletedData implements Serializable{
private Integer logId;
private String objectNameOrTableName ;
private byte[] ObjectValueOrTablevalue ;
public Integer getLogId() {
return logId;
}
public void setLogId(Integer logId) {
this.logId = logId;
}
public String getObjectNameOrTableName() {
return objectNameOrTableName;
}
public void setObjectNameOrTableName(String objectNameOrTableName) {
this.objectNameOrTableName = objectNameOrTableName;
}
public byte[] getObjectValueOrTablevalue() {
return ObjectValueOrTablevalue;
}
public void setObjectValueOrTablevalue(byte[] objectValueOrTablevalue) {
ObjectValueOrTablevalue = objectValueOrTablevalue;
}
}
Note: Please observe the representation of a blob type in PermanentlyDeletedData Model, here we represented as byte[].
And provided setter and getters as per byte[]
Step 4:
Now consider below data for Company ,Employee tables
Company:
|
companyId
|
companyName
|
location
|
|
|
001
|
RAM TEXTTILES
|
Hyderabad
|
|
|
002
|
Cheekuri Solutions
|
Hyderabad
|
|
|
003
|
Tri Institutions
|
Hyderabad
|
|
|
Employee
|
empId
|
empName
|
desigantion
|
department
|
companyId
|
|
|
100
|
RAM
|
Software developer
|
Java
|
002
|
|
|
101
|
Nim
|
Software developer
|
Java
|
002
|
|
|
102
|
rag
|
Software developer
|
Java
|
001
|
|
|
|
|
Now , I want delete the company cheekuri solutions from the table Company and it’s associated date which is there in the Employee table and this same data I want to store in the PermanentlyDeletedData table
Step 5:
Serilization Of Object
public void serilizeOrStoringObject(){
PermanentlyDeletedData permanentlyDeletedData=new PermanentlyDeletedData();
Company company = new Company();
Integer companyId = 002;
List<Company> result = null;
result = getHibernateTemplate().findByNamedQuery(
"retrieveCompanyDetails", companyId);//This Query needs to be write in the hbm file as return the data as per the companyId
if (result != null && result.size() > 0) {
company = result.get(0);
}
permanentlyDeletedData.setObjectNameOrTableName("Company");
/*
* Serialize starts here
* Here we are taking one ByteArrayOutputStream and creating instance
* and passing this instance to an ObjectOutputStream
* and passing the required object to serilize here we are serilizing the company object(indirectly we are
* serializing company child objects i.e. Employee object also
* using teh writeObject ,write this object to baos Stream
* and converting to byteArray and placing into the permanentlyDeletedData using setObjectValueOrTablevalue
* property
*/
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(baos);
oout.writeObject(company);
oout.close();
permanentlyDeletedData.setObjectValueOrTablevalue(baos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
/*
* Deleting the comapny object from teh company table and inserting the permanentlyDeletedData into teh database using HibernateTemplte methods
*/
getHibernateTemplate().delete(company);
getHibernateTemplate().save(permanentlyDeletedData);
}
Once execution of above code we can find the data as like below
PermanentlyDeletedData:
logId
|
objectNameOrTableName
|
ObjectValueOrTablevalue
|
|
|
|
DeSerialization of Object
public void retrieveDeSerializeObject(Integer logId) {
// Validating the data whether DeSerilize or not
logId = 001;
PermanentlyDeletedData permanentlyDeletedData = new PermanentlyDeletedData();
List<PermanentlyDeletedData> result = null;
result = getHibernateTemplate().findByNamedQuery(
"retrievePermanentlyDeletedData", logId);//This Query needs to be write in the hbm file as return the data as per the logId
if (result != null && result.size() > 0) {
permanentlyDeletedData = result.get(0);
}
Company deletedCompany = null;
/*
* DeSerilize starts here
* Using the ByteInputStream and ObjectInputStream ,readObject of InputStream ,read the Company Object from the ByteArray
* From The Company Object ,we can access the actual data i.e. serialized data
* Employee records those are serialized or associated with the company object can be retrievable now
* Using teh getEmpSet method which is available in Company object represented using Hibernate Collections(Set)
*
*/
try {
byte[] buf = permanentlyDeletedData.getObjectValueOrTablevalue();//Placing the object value i.e blob datatype of DB into byte array
if (buf != null) {
ObjectInputStream objectIn;
objectIn = new ObjectInputStream(new ByteArrayInputStream(buf));
Object obj = objectIn.readObject(); // Contains the object
deletedCompany = (Company) obj;
System.out.println("Deleted Company Id after Deserilization is "+deletedCompany.getCompanyId()+"\t"+deletedCompany.getCompanyName()+"\t"+deletedCompany.getEmpSet().size());
Set<Employee> cset = deletedCompany.getEmpSet();
for (Employee emp : cset) {
System.out.println("Deleted emp id for the above company is "+emp.getEmpId());
System.out.println("Deleted emp name for the above company is "+emp.getEmpName());
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Below is the actual DAO class for both Serilize and DeSerialize of Object
Or
Storing the java Object into the Database Using Hibenrate
package com.ram.tri.serilization;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Set;
public class SerializeDAO extends HibernateDaoSupport {
public void serilizeOrStoringObject(){
PermanentlyDeletedData permanentlyDeletedData=new PermanentlyDeletedData();
Company company = new Company();
Integer companyId = 002;
List<Company> result = null;
result = getHibernateTemplate().findByNamedQuery(
"retrieveCompanyDetails", companyId);//This Query needs to be write in the hbm file as return the data as per the companyId
if (result != null && result.size() > 0) {
company = result.get(0);
}
permanentlyDeletedData.setObjectNameOrTableName("Company");
/*
* Serialize starts here
* Here we are taking one ByteArrayOutputStream and creating instance
* and passing this instance to an ObjectOutputStream
* and passing the required object to serilize here we are serilizing the company object(indirectly we are
* serializing company child objects i.e. Employee object also
* using teh writeObject ,write this object to baos Stream
* and converting to byteArray and placing into the permanentlyDeletedData using setObjectValueOrTablevalue
* property
*/
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(baos);
oout.writeObject(company);
oout.close();
permanentlyDeletedData.setObjectValueOrTablevalue(baos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
/*
* Deleting the comapny object from teh company table and inserting the permanentlyDeletedData into teh database using HibernateTemplte methods
*/
getHibernateTemplate().delete(company);
getHibernateTemplate().save(permanentlyDeletedData);
}
public void retrieveDeSerializeObject(Integer logId) {
// Validating the data whether DeSerilize or not
logId = 001;
PermanentlyDeletedData permanentlyDeletedData = new PermanentlyDeletedData();
List<PermanentlyDeletedData> result = null;
result = getHibernateTemplate().findByNamedQuery(
"retrievePermanentlyDeletedData", logId);//This Query needs to be write in the hbm file as return the data as per the logId
if (result != null && result.size() > 0) {
permanentlyDeletedData = result.get(0);
}
Company deletedCompany = null;
/*
* DeSerilize starts here
* Using the ByteInputStream and ObjectInputStream ,readObject of InputStream ,read the Company Object from the ByteArray
* From The Company Object ,we can access the actual data i.e. serialized data
* Employee records those are serialized or associated with the company object can be retrievable now
* Using teh getEmpSet method which is available in Company object represented using Hibernate Collections(Set)
*
*/
try {
byte[] buf = permanentlyDeletedData.getObjectValueOrTablevalue();//Placing the object value i.e blob datatype of DB into byte array
if (buf != null) {
ObjectInputStream objectIn;
objectIn = new ObjectInputStream(new ByteArrayInputStream(buf));
Object obj = objectIn.readObject(); // Contains the object
deletedCompany = (Company) obj;
System.out.println("Deleted Company Id after Deserilization is "+deletedCompany.getCompanyId()+"\t"+deletedCompany.getCompanyName()+"\t"+deletedCompany.getEmpSet().size());
Set<Employee> cset = deletedCompany.getEmpSet();
for (Employee emp : cset) {
System.out.println("Deleted emp id for the above company is "+emp.getEmpId());
System.out.println("Deleted emp name for the above company is "+emp.getEmpName());
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Let me know if you find any difficulties or queries , just shoot me on ram.ch9@gmail.com