Tuesday, July 05, 2005

How to write a Java Object to a database blob column

This snippet describes how to write a Java Object to a database BLOB column, then read it back. The Java Object must be Serializable so that it can be represented as a byte array for either writing or reading.

First, writing to a blob column. For this example, there is a table called blobtable. It contains a BLOB colunm called blobcolumn. The way to write it to the DB is to assign the Serializable to a byte array, then write that byte array to the DB.


public void saveObjectToBlob(
        Connection conn,
        Serializable saveObject)
throws IOException, SQLException {

    PreparedStatement stmt = null;
    String query =
        "INSERT " +
        "INTO blobtable (" +
        " blobcolumn) VALUES (" +
        " ?) ";

    stmt = conn.prepareStatement(query);

    // write the object content to a byte array
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(saveObject);
    oos.close();
    byte saveObjectBy[] = bos.toByteArray();
    stmt.setBytes(1, saveObjectBy);
    // Oracle converts it to BLOB automatically

    stmt.executeUpdate();
}


After writing it to the blob column, you can read it back. The way to read it back is to use the Blob interface for the DB blob column. Read it back as byte array, then cast that to Serializable. Then cast the Serializable to the original Object type.


public Serializable readObjectFromBlob(Connection conn)
throws SQLException, IOException, ClassNotFoundException {

PreparedStatement pstmt = null;
ResultSet rset = null;
String query =
"SELECT " +
" blobcolumn " +
"FROM " +
" blobtable ";

pstmt = conn.prepareStatement(query);
rset = pstmt.executeQuery();
Serializable result = null;
if (rset.next()) {
byte blobcolumnBy[];
Blob bl = rset.getBlob(1);
blobcolumnBy = bl.getBytes(1, (int) bl.length());

ByteArrayInputStream bis =
new ByteArrayInputStream(blobcolumnBy);
ObjectInputStream ois = new ObjectInputStream(bis);
Object obj = ois.readObject();
ois.close();
result = (Serializable) obj;
}

return result;
}

No comments: