读书人

向Oracle中安插BLOB类型

发布时间: 2012-08-21 13:00:21 作者: rapoo

向Oracle中插入BLOB类型
使用s2sh框架。实体类:

public class Photo implements java.io.Serializable {// Fieldsprivate 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<Mark> facelookmarks = new ArrayList<Mark>();private Set facelookactivities = new HashSet(0);private List<Comment> facelookcomments = new ArrayList<Comment>();}

Photo.hbm.xml
<property name="content" type="java.sql.Blob">            <column name="CONTENT" />        </property>        <property name="thumbnail" type="java.sql.Blob">            <column name="THUMBNAIL" />        </property>

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 sqlgetSession().refresh(photo, LockMode.UPGRADE);// 通过refresh方法,强制Hibernate执行select for update

这样在hibernate中就讲图片插入到数据库中了。
在JDBC中,需要先把BLOB字段插入空值,通过oracle.sgl.BLOB.empty_lob()方法构造空Blob对象。再次从库表读出,获得Blob句柄,然后将byte[]数组写入blob。

读书人网 >编程

热点推荐