对于jdbc来讲,处理clob/blob时一件比较复杂的事情,通常,我们采用的是:第一步插入一个空值,第二部锁住此行,第三步更新clob/blob字段,其实,随着驱动的不端的更新,给了我们直接操作clob和blob字段的方法:
环境:oracle10(ojdbc14.jar)
一:建表
create table hibclobblob(
id number not null primary key,
tname clob,
image blob);
二:映射文件
<hibernate-mapping>
<class name="com.jack.clobblob.Hibclobblob" table="HIBCLOBBLOB" schema="ZZJ">
<id name="id" type="java.lang.Long">
<column name="ID" precision="22" scale="0" />
<generator class="increment" />
</id>
<!-- 请注意这里type需要修改成text-->
<property name="tname" type="text">
<column name="TNAME" />
</property>
<!--请注意这里type需要修改成blob-->
<property name="image" type="blob">
<column name="IMAGE" />
</property>
</class>
</hibernate-mapping>
三:pojo
public class Hibclobblob implements java.io.Serializable {
private Long id;
private String tname; //clob类型可以直接用string,很奇怪吧
private Blob image; //需要修改成blob类型,默认是String
get,set方法
四:测试类
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Blob;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class BlobClobOp {
private static SessionFactory sessionFactory = null;
private static Session session = null;
static {
Configuration config = new Configuration().configure();
sessionFactory = config.buildSessionFactory();
}
public static void addClobBlob() {
try {
session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
Hibclobblob clobblob = new Hibclobblob();
StringBuffer str = new StringBuffer();
for(int i=0;i<10000;i++) {
str.append("webshpere 部署丢文件问题,打包时候存在,部署到服务器就少文件了");
}
clobblob.setTname(str.toString());
FileInputStream stream = new FileInputStream("h://aaa.jpg");
Blob blob = Hibernate.createBlob(stream);
clobblob.setImage(blob);
session.save(clobblob);
transaction.commit();
session.close();
} catch (HibernateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String arg[]) {
addClobBlob();
}
}
现在可以看一下结果
SQL> select dbms_lob.getlength(image) from hibclobblob where id = 1;
DBMS_LOB.GETLENGTH(IMAGE)
-------------------------
880000
SQL> select dbms_lob.getlength(tname) from hibclobblob where id = 1;
DBMS_LOB.GETLENGTH(TNAME)
-------------------------
1221490
说明成功了
是不是很简单!
简单是简单,不过还是有些不足的,对于老的数据库驱动,以上程序是不能运行的,如class12.jar