0

当我尝试使用 (Blob) 将 Oject 转换为 blob 时,得到 java.lang.ClassCastException: [B cannot be cast to java.sql.Blob 错误。

但是当我尝试使用以下代码进行转换并写入图像文件时,图像已损坏。

Blob blob = null;

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = null;
        try {
          out = new ObjectOutputStream(bos);   
          out.writeObject(myObj);

          byte[] yourBytes = bos.toByteArray();

          //blob.setBytes(1, yourBytes );
          blob = new SerialBlob(yourBytes);
        } finally {
          out.close();
          bos.close();
        }

如何安全地将对象(保存为 Blob 的图像文件)转换为 Blob?

注意:由于要求,我只能作为从其他部分传递的对象。

4

3 回答 3

1

您可以使用

如果你使用休眠

      Blob blob = Hibernate.createBlob(bytes, session); 

如果您使用的是 JDBC

       Blob blob = connection.createBlob();
       blob.setBytes(1, bytes);
于 2013-04-04T04:34:02.510 回答
0

由于您收到的类演员异常,我将在这里四处走动并说您实际上并没有从那一端得到一个 Blob。

进行调试并查看实际发送的类型。

而且我可能错了,但据我所知,Clob 和 Blob 不可序列化......所以如果另一端是网络,它将是 kaboom......

于 2013-04-04T03:43:48.340 回答
0

不确定我的答案有多相关,但已使用上述答案作为提示来达到这一点。

使用 - 下面的依赖

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.1.0.Final</version>
</dependency>

模型类中的属性定义为 -

java.sql.Blob message;

mymodel.hbm.xml有效模型映射内的文件中

<class name="packagepath.Pojo" table="pojotableindb">
<meta attribute="class-description">
     Pojo class is mapped to pojotableindb table
  </meta>
    <id name="id" column="ID" type="long">
    <!-- for auto increment -->
        <generator class="identity" />
    </id>
    <property name="message" column="MESSAGE" type="blob" />
</class>

现在,在我的一个 DAO 方法中,我做了如下的事情来在MESSAGE列中插入一个值 -

Pojo pojo = new Pojo();
pojo.setMessageId(uuid);
//message is the string argument this DAO method receives         
activityTrack.setMessage(Hibernate.getLobCreator(session).createBlob(message.getBytes())); 

tx = session.beginTransaction();
session.save(pojo);
tx.commit(); 

希望这会对某人有所帮助。

于 2016-09-05T10:00:52.763 回答