Sunday, January 5, 2020

Serialize object to database

Serializing Objects into Database:
  • Stream the object to a ByteArrayOutputStream via an ObjectOutputStream.
  • Convert the ByteArrayOutputStream to a byte array.
  • Call the setBytes method on the prepared statement.
To de-serialize a java object from database:
  • Read the byte array and put it into a ByteArrayInputStream
  • Pass that to an ObjectInputStream
  • Then read the object.
Let's create an example of employee class object,this sample java source code below to serialize and de-serialize java object to mysql database.

Create database to test this example.
create database javaserialization;
create table BlobTable(`serialized_object` blob);  

Employee.java
import java.io.Serializable;

public class Employee {
 long empId;
 String name;
 int age;

 public Employee() {
 }

 public Employee(long empId, String name, int age) {
  this.empId = empId;
  this.name = name;
  this.age = age;
 }

 public long getEmpId() {
  return empId;
 }

 public void setEmpId(long empId) {
  this.empId = empId;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

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

 @Override
 public String toString() {
  return "Employee [age=" + age + ", empId=" + empId + ", name=" + name + "]";
 }

}

import java.sql.*;
import java.io.*;
import java.util.Vector;

public class SerializeToDatabase {

 // return byte array
 public static byte[] write(Object obj) throws SQLException, IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oout = new ObjectOutputStream(baos);
  oout.writeObject(obj);
  oout.close();
  return baos.toByteArray();
 }

 public static Object read(ResultSet rs, String column) throws SQLException, IOException, ClassNotFoundException {
  byte[] buf = rs.getBytes(column);
  if (buf != null) {
   ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(buf));
   return objectIn.readObject();
  }
  return null;
 }

 public static void main(String[] args) throws Exception {
  Class.forName("com.mysql.jdbc.Driver");
  Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javaserialization", "root", "root");

  Statement st = con.createStatement();
  st.executeUpdate("INSERT BlobTable (serialized_object) VALUES (NULL)");
  st.close();

  PreparedStatement ps = con.prepareStatement("INSERT INTO BlobTable (serialized_object) VALUES (?)");
  Employee employee = new Employee(1L, "Sanjeev", 21);
  // System.out.println(employee);
  ps.setBytes(1, write(employee));
  ps.execute();

  ps.setBytes(1, write(new Vector(2) {
   {
    add("Sanjeev");
    add("Gupta");
   }
  }));
  ps.execute();

  ps.setBytes(1, write(new Vector(2) {
   {
    add("Rajeev");
    add("Kumar");
   }
  }));
  ps.execute();

  /*
   * Vector veryBig = new Vector(10); for (int i = 0; i < 10; i++) {
   * veryBig.add(new byte[10000]); } write(veryBig, ps, 1); ps.execute();
   * write("What Gives?", ps, 1); ps.execute();
   */

  ps.setBytes(1, null);
  ps.execute();

  ps.close();

  // Read Object from database

  st = con.createStatement();
  ResultSet rs = st.executeQuery("SELECT serialized_object FROM BlobTable");
  while (rs.next()) {
   System.out.println(read(rs, "serialized_object"));
  }

  rs.close();
  st.close();
 }
}
Output:
Exception in thread "main" java.io.NotSerializableException: Employee
 at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
 at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
 at com.mkyong.common.SerializeToDatabase2.write(SerializeToDatabase2.java:15)
 at com.mkyong.common.SerializeToDatabase2.main(SerializeToDatabase2.java:40)

Note:- As you can see "Exception in thread "main" java.io.NotSerializableException: Employee" because i have not implements Serializable.
So to currect the above we need to implements Serializable interface in employee class.

Employee.java
import java.io.Serializable;

public class Employee implements Serializable {
 long empId;
 String name;
 int age;

 public Employee() {
 }

 public Employee(long empId, String name, int age) {
  this.empId = empId;
  this.name = name;
  this.age = age;
 }

 public long getEmpId() {
  return empId;
 }

 public void setEmpId(long empId) {
  this.empId = empId;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

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

 @Override
 public String toString() {
  return "Employee [age=" + age + ", empId=" + empId + ", name=" + name + "]";
 }

}
Output:
null
Employee [age=21, empId=1, name=Sanjeev]
[Sanjeev, Gupta]
[Rajeev, Kumar]
null

No comments:

Post a Comment