Hibernate2.X处理Clob字段

Posted on 2006-04-16 13:08  火鸟  阅读(331)  评论(0)    收藏  举报

    本文介绍的是Hibernate2.x在处理Oracle的Clob的几点经验:

1.Hibernate配置文件的写法:

        <property name="textValue" column="TEXT_VALUE" type="clob" length="100000"/>

首先,必须生命属性的type类型是Clob或者java.sql.Clob,并且一定要加上length的属性,指定字段的长度,否则在Oracle9的版本中,如果Clob的内容过大,在insert和update的时候会报错。
      补充:如果在Mysql或是Postgresql中,可以使用text来代替Clob类型,直接使用save和update方法。

2.代码的编写:

    public void update(DocumentData obj, String value)
   throws HibernateException, Exception
 {
  Session s = null;
  Writer out = null;
  try
  {
   s = getSession();
   s.flush();
   Transaction tx = s.beginTransaction();
   s.refresh(obj, LockMode.UPGRADE);//锁定更新记录;
   CLOB clob = (CLOB) obj.getTextValue();
   if (clob != null)
   {
    out = clob.getCharacterOutputStream();
    out.write(value);
    out.flush();//刷新内容,同步session和数据库内容。
    out.close();
   } else
   {
    obj.setTextValue(Hibernate.createClob(value == null ? ""
      : value));
   }
   tx.commit();
  } finally
  {
   if (null != s)
   {
    s.close();
   }
   if (out != null)
   {
    out.close();
   }
  }
 }

 public void insert(DocumentData obj)
   throws HibernateException, Exception
 {
      Transaction t = null;
  Session s = null;
  try {
   s = getSession();
   t = s.beginTransaction();
   s.save(obj);//obj对象包含Clob属性内容,可以直接insert
   t.commit();
  }
  catch (HibernateException e) {
   if (null != t) t.rollback();
            throw e;
  }
  finally {
   if (null != s) s.close();
  }
 }
3。最重要的是要使用Oracle10的JDBCDriver,代替Oralce9的JDBCDriver。

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3