Serialize a bean using jdbc

Posted by Enrico Giurin Wed, 11 Jan 2006 00:19:00 GMT

Sometimes, in my work as programmer, I need to serialize an object (bean) into a table, in a BLOB field, as well as retrieves bean from a ResultSet. I have realized a simple example that, using JDBC, allows to obtain this.

Here the method to fill PreparedStatement :

public static void fillPreparedStatement(PreparedStatement pst, int index,
         Serializable obj) throws Exception {

      if (obj != null) {
         ByteArrayOutputStream regStore = new ByteArrayOutputStream();

         ObjectOutputStream regObjectStream = new ObjectOutputStream(regStore);
         regObjectStream.writeObject(obj);
         byte[] regBytes = regStore.toByteArray();
         regObjectStream.close();
         regStore.close();
         ByteArrayInputStream regArrayStream = new ByteArrayInputStream(regBytes);
         pst.setBinaryStream(index, regArrayStream, regBytes.length);
      }// end of if
      else {
         pst.setNull(index, Types.BLOB);
      }
}// end of method

Here the method to retrieve bean from ResultSet.

public static Object getFromResultSet(ResultSet rs, String columnName)
         throws Exception {
      byte[] regBytes = rs.getBytes(columnName);
      ByteArrayInputStream regArrayStream = new ByteArrayInputStream(regBytes);
      ObjectInputStream regObjectStream = new ObjectInputStream(
            regArrayStream);
      return regObjectStream.readObject();
}

I tested this code using MySQL 4.1 db. Hope this example could save your valuable time. Enrico.

Posted in  | Tags , ,  | 2 comments

Comments

  1. Avatar null said about 2 hours later:

    Reached your method via google - quite an interesting one! Should you ever post other related examples i’dbe gladily catching on them

  2. Avatar Enrico Giurin said about 20 hours later:

    I tested this code with oracle and it failed. In order to solve the problem I change oracle type from BLOB to LONG RAW and, with the same java code, it works with success. So, for this example with Oracle, it’s better use LONG RAW type, instead of BLOB type.

(leave url/email »)

   Comment Markup Help Preview comment