向Oracle中插入BLOB类型
使用s2sh框架。实体类:
public class Photo implements java.io.Serializable {
// Fields
private Integer id;
private Album album;
private Timestamp createtime;
private String name;
private String contentType;
private Blob thumbnail;
private Blob content;
private Integer orderid;
private List facelookmarks = new ArrayList();
private Set facelookactivities = new HashSet(0);
private List facelookcomments = new ArrayList();
}
Photo.hbm.xml
action
FileInputStream fis = new FileInputStream(this.photoUpload);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n=fis.read(b)) != -1) {
out.write(b,0,n);
}
fis.close();
out.close();
byte[] content = out.toByteArray();
this.photo.setAlbum(this.album);
this.photo.setContentType(this.photoUploadContentType);
this.photo.setCreatetime(new Timestamp(System.currentTimeMillis()));
this.photo.setOrderid(orderId);
this.photo.setContent(Hibernate.createBlob(content));
this.photo.setThumbnail(Hibernate.createBlob(thumbnail));
this.photoUpload为上传的文件。将得到的byte[]数组通过Hibernate.createBlob方法赋值给content和thumbnail属性。
PhotoDAO
getSession().save(photo);
getSession().flush();// 调用flush方法,强制Hibernate立即执行insert sql
getSession().refresh(photo, LockMode.UPGRADE);// 通过refresh方法,强制Hibernate执行select for update
这样在hibernate中就讲图片插入到数据库中了。
在JDBC中,需要先把BLOB字段插入空值,通过oracle.sgl.BLOB.empty_lob()方法构造空Blob对象。再次从库表读出,获得Blob句柄,然后将byte[]数组写入blob。