I found this “Serialization in Java/J2EE” from Enterprise Java In Action. I decided to write a code example to implement the “Read and write serialized objects to and from a database”. Here is

import java.util.*;
import java.io.*;
import com.myapps.*;

public final class Shop implements Serializable {
      private long storeId;
      private Location address;

      public Shop () {}	

      /**
       *  Serialized shop and save to database
       */
      public void saveShopBlobToDB() throws Exception {
	ByteArrayOutputStream baStream = new ByteArrayOutputStream();
	ObjectOutputStream outStream = new ObjectOutputStream(baStream);
	outStream.writeObject(this);
        outStream.flush();
	byte[] data = baStream.toByteArray();

	Connection conn = null;
	PreparedStatement stmt = null;
	try {
	  conn = DatasourceManager.getConnection();//assume to get JDBC connection
	  stmt = conn.prepareStatement("INSERT INTO ShopBlob(blobData) VALUES (?)");
	  stmt.setObject(1, data);
	  stmt.executeUpdate();
	} catch (Exception ex){
	  //not comeplete code here...
	  throw ex;
	} finally{
	  //not comeplete code here...
	  stmt.close();
	  conn.close();
	}
      }

      /**
       *  Read shop Blob from database and deserialized
       */
      public Shop readShopBlobFromDB(long ShopId) throws Exception {
      	Connection conn = null;
      	PreparedStatement stmt = null;
      	ResultSet rs = null;
      	try {
      	  conn = DatasourceManager.getConnection();//assume to get JDBC connection
      	  stmt = con.prepareStatement("SELECT blobData FROM ShopBlob WHERE id = ?");
	  stmt.setString(1, shopId);
          rs = stmt.executeQuery();
      	  Blob b = rs.getBlob(1);
      	  byte[] data = b.getBytes(0, (int) b.length());
      	  ByteArrayInputStream bais = new ByteArrayInputStream(data);
      	  ObjectInputStream ois = new ObjectInputStream(bais);
	  return (Shop) ois.readObject();
      	} catch (Exception ex){
      	  //not comeplete code here...
      	  throw ex;
      	} finally{
      	  //not comeplete code here...
      	  rs.close();
      	  stmt.close();
      	  conn.close();
      	}
      }
}

Ref:
Blob: JDBC deals with Binary Data

XML serialization:
XStream and Spring OXM (Object/XML Mapping framework)

Thoughts on Web Services, part 5: To serialize or not to serialize

Advertisements