使用hibernate将ArrayList设置为java.sql.Blob以保存在DB中很困难
我试图通过将 java ArrayList 设置为 blob 将其保存在数据库(H2)中,以便稍后检索。如果这是一个不好的方法,请说 - 我无法找到有关该领域的太多信息。
我在数据库中有一个 Blob 类型的列,Hibernate 使用 java.sql.Blob 映射到该列。我正在努力解决的代码是:
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);
}
我试图保存到 blob 中的对象 (plan.drawingPane21.pointList
) 的类型为 ArrayList
, < code>DrawingDot 是一个实现 Serialized
的自定义类。
我的代码在 drawingBlob.setBytes(0, buff);
行上失败,并出现 NullPointerException
。
帮助表示赞赏。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你从未初始化过变量drawingBlob:
我对Hibernate的了解非常有限,但我相信如果数据类型映射到Blob,那么hibernate将为你执行序列化,这作为在a中设置数据的标准方法是有意义的。 blob 是通过参数化的PreparedStatement 中的方法实现的。
You have never initialized the variable drawingBlob:
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.
如果有人遇到同样的问题,我通过利用 SerialBlob 类的构造函数而不是使用 setBytes 来解决它:
In case anyone is having the same problem, I solved it by taking advantage of the
SerialBlob
class's constructor rather than using setBytes: