views:

244

answers:

2

I'm trying to save a java ArrayList in a database (H2) by setting it as a blob, for retrieval later. If this is a bad approach, please say - I haven't been able to find much information on this area.

I have a column of type Blob in the database, and Hibernate maps to this with java.sql.Blob. The code I'm struggling with is:

Drawings drawing = new Drawings();

try {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = null;
    oos = new ObjectOutputStream(bos);
    oos.writeObject(plan.drawingPane21.pointList);
    byte[] buff = bos.toByteArray();
    Blob drawingBlob = null;
    drawingBlob.setBytes(0, buff);
    drawing.setDrawingObject(drawingBlob);
} catch (Exception e){
    System.err.println(e);
}

The object I'm trying to save into a blob (plan.drawingPane21.pointList) is of type ArrayList<DrawingDot>, DrawingDot being a custom class implementing Serializable.

My code is failing on the line drawingBlob.setBytes(0, buff); with a NullPointerException.

Help appreciated.

A: 

You have never initialized the variable drawingBlob:

Blob drawingBlob = null;//<- not initialized
drawingBlob.setBytes(0, buff);//<- drawingBlob is null here.

My knowledge of Hibernate is very limited, but I believe that if the data type is mapped to a Blob then hibernate will perform the serialization for you, which makes sense as the standard way to set data in a blob is via the methods in a parametrized PreparedStatement.

M. Jessup
+1  A: 

In case anyone is having the same problem, I solved it by taking advantage of the SerialBlob class's constructor rather than using setBytes:

byte[] buff = bos.toByteArray();
Blob drawingBlob = null;
drawingBlob = new SerialBlob(buff);
drawing.setDrawingObject(drawingBlob);
me_here