使用Hibernate处理Oracle中的Blob字段


1. Bolb类型字段说明:

写入Blob字段和写入其它类型字段的方式非常不同,因为Blob自身有一个cursor,你必须使用cursor对blob进行操作,因而你在写入Blob之前,必须获得cursor才能进行写入,那么如何获得Blob的cursor呢?

这需要你先插入一个empty的blob,这将创建一个blob的cursor,然后你再把这个empty的blob的cursor用select查询出来,这样通过两步操作,你就获得了blob的cursor,可以真正的写入blob数据了。

2. Bolb类型字段保存:

Hibernate的配置文件就不写了 ,需要将Blob字段了类型设为java.sql.Blob,下面直接上代码

 public void save(ZyglBlxx bean, InputStream ins) throws WebServiceException {
  // TODO Auto-generated method stub
  Session session = this.getHibernateTemplate().getSessionFactory().openSession();
  //ins.
  //out.write(b)
  try {
   bean.setDoccontent(BLOB.getEmptyBLOB());
   
   Transaction tr = session.beginTransaction();
   bean.setVId(WebServiceEditUtils.getPk());
   session.save(bean);
   session.flush();
   session.refresh(bean, LockMode.UPGRADE);
   if(ins!=null){
    SerializableBlob sb = (SerializableBlob)bean.getDoccontent();
    BLOB b = (BLOB)sb.getWrappedBlob();
   
    OutputStream out = b.getBinaryOutputStream();
   
    int len=-1;
    byte[] bt = new byte[2048];        //可以根据实际情况调整,建议使用1024,即每次读1KB
    while((len=(ins.read(bt))) != -1)      {
     out.write(bt,0,len);                    //建议不要直接用os.write(bt)
    }
    out.flush();
    ins.close();
    out.close();
   }
   session.flush();
   tr.commit();
   session.close();
  } catch (IOException e) {
   e.printStackTrace();
   throw ExceptionManager.getExcption("18");
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   throw ExceptionManager.getExcption("19");
  }
 }

为了保存文件时比较方便我这里的参数直接接收为InputStream,其他类型类似

Hibernate 的详细介绍:请点这里
Hibernate 的下载地址:请点这里

Hibernate 中文手册 PDF

  • 1
  • 2
  • 下一页

相关内容