利用Hibernate Synchronizer插入oralce.CLOB字段
2024-07-21 02:40:10
供稿:網(wǎng)友
表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,在運(yùn)行時(shí),會(huì)拋出異常net.sf.hibernate.MappingException: Error reading resource: Info.hbmnet.sf.hibernate.MappingException: Error reading resource: Info.hbm。我也不明白為什么,估計(jì)是找不到包,假如那位知道,請(qǐng)告訴我?。┫旅媸窍鄳?yīng)的代碼片斷: // 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();不過這個(gè)方法是最笨的一個(gè)辦法,更好的辦法,或者說更透明的方法是通過實(shí)現(xiàn)net.sf.hibernate.UserType接口,來自定義處理oracle.CLOB類型的類。這種方法仍然在研究中:)。雖然說這個(gè)方法比較落后,但是,最起碼現(xiàn)在可以通過hibernate插入oracle.CLOB字段了!