在Spring+Hibernate处理Oracle lob字段(一) 中说明了使用spring+hibernate处理lob字段的方式,这里在说明一下使用另一种方式处理lob字段(以clob为例)。
首先,将Pojo里面的属性定义为clob类型:
protected Clob contentClob;
hibernate.hbm.xml配置如下:
<property name="contentClob" column="contents"
type="java.sql.Clob"/>
Dao使用的方法如下:
public <T> void update(final T entity) throws Exception {
getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
entity.setContentClob(Hibernate.createClob(" "));
session.update(entity);
session.flush();
session.refresh(entity, LockMode.UPGRADE);
SerializableClob serializableClob =
(SerializableClob)entity.getContentClob();
Clob clob = serializableClob.getWrappedClob();
if (clob instanceof oracle.sql.CLOB) {
//此处要转化成Oracle.sql.CLOB类型
java.io.Writer writer =
((oracle.sql.CLOB)clob).getCharacterOutputStream();
try {
if (entity.getContents() != null
&& !"".equals(entity.getContents())) {
writer.write(entity.getContents());
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException();
} finally {
try {
writer.close();
writer = null;
} catch (IOException e) {
}
}
}
session.flush();
//session.connection().commit();
return null;
}
}
);
}
使用以上的方式也能正确的插入和更新Clob字段而不用升级JDBC驱动。由于这里要采用两步操作(先插入,再更新)实现,所以要加上事务管理,使用spring的声明式事务即可。
注意:
1.Pojo中要加个字符串类型的属性,如:
protected String contents;
用于存放将要保存到CLOB中的内容。
2.POJO中增加一个方法,用户转换Clob的内容为String
public String getContentClobToString() {
if (this.contentClob != null && !"".equals(this.contentClob.toString().trim())) {
try {
return this.contentClob.getSubString(1L, (int)this.contentClob.length());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "";
}