Wednesday, December 12, 2007

How to "serialize to" and "retrieve from" objects from hsqldb

Assuming ChartData implements the serializable interface:


String insertGraph ="INSERT INTO GRAFICI_BLOB (ID, DATA) VALUES (##, ?)"

ChartData chartData = chartsPage.getChartData();
// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(chartData);
out.close();
} catch (IOException e2) {
e2.printStackTrace();
}
byte[] chartDataBytes = bos.toByteArray();

PreparedStatement str1 = null;
try {
str1 = con.prepareStatement(insertGraph);
str1.setBytes(1, chartDataBytes);
str1.executeUpdate();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (null != str1)
str1.close();
} catch (Exception ex) {
}

}

/*
* and the way back
*/
Statement stmt = con.createStatement();
String sql = the query to select your blob field... (in my case GRAFICO)

ResultSet res = stmt.executeQuery(sql);
byte[] bytes = res0.getBytes("GRAFICO");
// Deserialize from byte array
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
runProperties.chartData = (ChartData) in.readObject();
in.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

No comments: