假设一个Student类的代码如下:
import java.sql.Blob;
import java.sql.Clob;
public class Student {
    private String id; //主键id
    private String name; //名字
    private Integer age; //年龄
    private Blob photo; //照片
    private Clob describe; //对此学生的描述
//省略get和set方法
}
在进行对象保存时,可以使用Hibernate.createBlob()与Hibernate.createClob()从来源数据建立Blob与Clob实例,例如下面的代码将一幅照片和一段文本保存到数据库:
//新建并保存Student实例
FileInputStream fileInputStream = new FileInputStream("src\\sample.jpg");
Blob photo = Hibernate.createBlob(fileInputStream);
Clob describe = Hibernate.createClob("he is so good student");
stu.setName("tomclus");
stu.setAge(new Integer(30)); //设置年龄
stu.setPhoto(photo); //设置照片
stu.setDescribe(describe); //设置描述
session.save(stu);
……//提交事务,关闭session

解决方案 »

  1.   

    换应用的jdbc包,换成10g或以上
      

  2.   

    是10g的jdbc包,但偶尔还会出现异常
      

  3.   

    先保存一次,随便放个字节保存了
    byte[] buffer = new byte[1];
    buffer[0] = 1;
    stu.setPhoto(Hibernate.createBlob(buffer));
    session.save(stu);
    session.flush();
    //然后再更新, 代码比较怪,针对websphere+oracle
    s.refresh(stu, LockMode.UPGRADE);
    SerializableBlob blob = (org.hibernate.lob.SerializableBlob) stu.getPhoto();
    Blob wb = blob.getWrappedBlob();
    if (wb instanceof BLOB) {
                BLOB image = (BLOB) wb;
                OutputStream out = image.getBinaryOutputStream();
                out.write(file1.getFileData());   //这里自己改成你的数据
                out.close();
                s.flush();
    } else {
                log.fatal("保存件失败, Blob类型不是oracle.sql.BLOB, 是 " +
                          wb.getClass().getName());
    }
      

  4.   

    还要继续请教楼上,如何取数据啊,我用load(id)方法取得实体对象,然后getPhoto()方法取得数据,结果无法打开了,我想应该是编码方式变了,请问楼上用什么方法取数据啊,我想直接把图片显示在前端,请多多指教,不胜感激!!!
      

  5.   

    这个给你参考吧, ZP0000就是照片
      public byte[] readBLOB(String gjz) throws SQLException, IOException {
        Session s = HibernateUtil.currentSession();
        ZP0000 zp = (ZP0000) s.get(ZP0000.class, gjz);
        if(zp==null) {
          return null;
        }    InputStream in = zp.getZp0000().getBinaryStream();    Blob wb = ((SerializableBlob)zp.getZp0000()).getWrappedBlob();
        int bufferSize = 0;
        if (wb instanceof BLOB) {
          bufferSize = ( (oracle.sql.BLOB) wb).getBufferSize();
        }
        else {
          log.fatal("保存照片失败, Blob类型不是oracle.sql.BLOB, 是 " + wb.getClass().getName());
          return null;
        }    ByteArrayOutputStream out = new ByteArrayOutputStream();    byte[] b = new byte[ (int) bufferSize];
        int count = in.read(b, 0, (int) bufferSize);
        int amount = 0;
        while (count != -1) {
          out.write(b, 0, count);
          amount += count;
          count = in.read(b, 0, (int) bufferSize);
        }
        out.close();
        in.close();
        return out.toByteArray();
      }