0

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.

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.