利用Hibernate Synchronizer插入oralce.CLOB字段

发表于:2007-06-22来源:作者:点击数: 标签:
表info的映射文件info.xml为: ?xml version=1.0? !DOCTYPE hibernate-mapping PUBLIC -//Hibernate/Hibernate Mapping DTD//EN http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd hibernate-mapping class name=src.Info table=INFO id column=I

   

表info的映射文件info.xml为:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD//EN"

 "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

<hibernate-mapping>
 <class name="src.Info" table="INFO">
  <id
   column="INFO_ID"
   name="Id"
   type="integer"
  >
   <generator class="vm">
                <!--param name="INFO">info_id</param-->
                <!--param name="INFO_ID">next_hi_value_column</param-->
         </generator>

  </id>
  <property
   column="INFO_CONT"
   name="InfoCont"
   not-null="false"
   type="java.sql.Clob"
   />
  <property
   column="INFO_AREA"
   length="100"
   name="InfoArea"
   not-null="false"
   type="string"
   />
  <property
   column="INFO_DATE"
   length="7"
   name="InfoDate"
   not-null="false"
   type="date"
   />
 </class>
</hibernate-mapping>

其中红色字体为要映射的oracle.CLOB类型。(在这里将其类型定义为java.sql.Clob类型,如果定义为oracle.CLOB,在运行时,会抛出异常net.sf.hibernate.MappingException: Error reading resource: Info.hbmnet.sf.hibernate.MappingException: Error reading resource: Info.hbm。我也不明白为什么,估计是找不到包,如果那位知道,请告诉我!)

下面是相应的代码片断:

        // Load the configuration file
        _RootDAO.initialize();
               
        // Create a instance of Info represents a new info to be added

        Info newInfo = new Info(new Integer(id));
        newInfo.setInfoArea(infoArea);
        newInfo.setInfoDate(Calendar.getInstance().getTime());
        InfoDAO infoDao = new InfoDAO();

        Session s = _RootDAO.createSession();
        Transaction tx = s.beginTransaction();
        

        // Insert a empty value into info_cont first
        newInfo.setInfoCont(Hibernate.createClob(" ") );
        s.save(newInfo);
        s.flush();

        // Lock the relative row
        s.refresh(newInfo, LockMode.UPGRADE);
        CLOB clob = (CLOB) newInfo.getInfoCont();
        java.io.Writer pw = clob.getCharacterOutputStream();
        try {
            pw.write(infoCont);// Write the CLOB value into table
            pw.close();
        } catch(IOException e) {
            throw new HibernateException(e);
        }
       
        tx.commit();
        s.close();

不过这个方法是最笨的一个办法,更好的办法,或者说更透明的方法是通过实现net.sf.hibernate.UserType接口,来自定义处理oracle.CLOB类型的类。这种方法仍然在研究中:)。虽然说这个方法比较落后,但是,最起码现在可以通过hibernate插入oracle.CLOB字段了!

原文转自:http://www.ltesting.net