Sometimes developers need to store their Java class object in database. This tip demonstrate how we can store object into database and again access the stored Java object.
//Creating a simple class. public class SimpleExample implements Serializable{ //Member variable. private int intValue; private String string; public void setIntValue(int intValue){ this.intValue = intValue; } public void setString(String string){ this.string = string; } public int getIntValue(){ return this.intValue; } public String getString(){ return this.string; } } /* * creating a class which have two function getByteArrayObject and getJavaObject. * * getByteArrayObject convert java object into byte[] and return the byte[]. * * getJavaObject convert byte[] to java object. and return SimpleExample object. * */ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class ConvertObject { //converting SimpleExample object to byte[]. public byte[] getByteArrayObject(SimpleExample simpleExample){ byte[] byteArrayObject = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(simpleExample); oos.close(); bos.close(); byteArrayObject = bos.toByteArray(); } catch (Exception e) { e.printStackTrace(); return byteArrayObject; } return byteArrayObject; } //converting byte[] to SimpleExample public SimpleExample getJavaObject(byte[] convertObject){ SimpleExample objSimpleExample = null; ByteArrayInputStream bais; ObjectInputStream ins; try { bais = new ByteArrayInputStream(convertObject); ins = new ObjectInputStream(bais); objSimpleExample =(SimpleExample)ins.readObject(); ins.close(); } catch (Exception e) { e.printStackTrace(); } return objSimpleExample; } } /** * * Writing a main class to converting the objects. * **/ public class MainClass { public static void main(String[] a) { SimpleExample simpleExample = new SimpleExample(); simpleExample.setIntValue(11); simpleExample.setString("This is intance of SimpleExample"); ConvertObject convertObject = new ConvertObject(); byte[] byteArrayObject = convertObject.getByteArrayObject(simpleExample); // Now we have byte[] to store in database. byte[] easly can stored into blob or Longblog field of database. // Retive byte[] from the database. //Now agian change the byte[] into SimpleExample class object. SimpleExample convertedSimpleExample = convertObject.getJavaObject(byteArrayObject); System.out.println("<------------------------------------------------------------->"); System.out.println(convertedSimpleExample.getIntValue() + " :: " + convertedSimpleExample.getString()); System.out.println("<------------------------------------------------------------>"); } }