Hibernate 保存Clob 和Blob

注意:目前只能操作Clob,因为不想用Session直接操作!

Clob在数据库中一般都是用来保存大文本字段的,Blob则是保存二进制流这样的!

1、Hibernate操作Clob字段
A.在实体Bean中将Clob字段声明为String类型。
  并声明get,set方法。
B.在实体Bean XML的配置文件中,将Clob字段类型为:text
C.在Oracle中,表字段的类型声明为:Clob。
那么在实际的操作中,java就吧相当于直接操作String类型并保存在Oracle的Clob中。
下面附带代码片段。
//声明Bean中的Clob字段类型为String ,属性名不一定要是clob。这里我顺便取的,呵呵
private String clob;
public String getClob() {
   return clob;
}
public void setClob(String clob) {
   this.clob = clob;
}
<property name="clob" column="clob" type="text" />

<!-- 在XXX.hbm.xml中,设置类型为text-->
<property name="clob" column="clob" type="text" />

inter.setClob("大文本!");

2.Hibernate 保存blob数据
//使用Session的方式保存
Session session = service.getCurrSession();
Transaction tran=session.beginTransaction();	
//首先定义一个空的blob对象保存在数据库中			inter.setPhoto(Hibernate.createBlob(new byte[100]));
session.save(inter);
session.flush();                              session.refresh(inter,LockMode.UPGRADE);
SerializableBlob   sb   =   (SerializableBlob)  inter.getPhoto();
//photo是图片的byte数组的形式
byte [] photo = (byte[]) intermap.get("photo");
BLOB blob = (BLOB)sb.getWrappedBlob(); 
//将某个文件读入后,写到Blob字段的输出流中
OutputStream os = blob.getBinaryOutputStream();
InputStream fis = new ByteArrayInputStream(photo);
byte[] buff = new byte[fis.available()];
fis.read(buff);
fis.close();
os.write(buff);
os.close();
session.flush();

/**
 * 使用Session操作大字段分为3步
 * 1、设置一个空的Clob/Blob保存到数据库中
 * inter.setPhoto(Hibernate.createBlob(new byte[100]));
 * 2、获得数据库中这个大字段的游标 (Clob/Blob的cursor)
 * session.refresh(inter,LockMode.UPGRADE);
 * 3、用cursor往数据库写数据
 * OutputStream os = blob.getBinaryOutputStream();
 * InputStream fis = new ByteArrayInputStream(photo);
 * byte[] buff = new byte[fis.available()];
 * fis.read(buff);
 * fis.close();
 * os.write(buff);
 * os.close();
 * session.flush();
**/

猜你喜欢

转载自sjeveryday.iteye.com/blog/1499851