在oracle 中 ,有時varchar2 類型不能滿足對字段的存儲,這就需要 用 大類型數據存儲
如: blob
hibernate 對blob 字段操作步驟如下:
1、在java Bean 中 定義一字段
public class NewsEntry {
private Blob contents2 ;
private String content;
... get ,set 方法 (省略不寫)
}
2、寫映射文件
<property
name="contents2"
update="true"
insert="true"
access="property"
type="java.sql.Blob" // 類型必須是這樣的
column="CONTENT"
/>
3、把字符串寫入blob 並同步到數據庫
public void save() throws Exception {
OutputStream out;
try {
NewsEntry entry = new NewsEntry ();
entry.setContents2(Hibernate.createBlob(new byte[1]));
entry.setContent("你好");
session.save(entry);
session.flush();// 強制執行insert
// 通過refresh方法,強制Hibernate執行select for update
session.refresh(entry, LockMode.UPGRADE);
// 向Blog寫入實際內容
BLOB blob = (BLOB) entry.getContents2();
out = blob.getBinaryOutputStream();
byte [] buf = new byte[1];
if (entry != null) {
buf = entry.getContent()== null ? null:entry.getContent().getBytes("gbk");
}
out.write(buf);
out.close();
} catch (RuntimeException e) {
throw new Exception(e);
}
}
通過這幾步就可以把字符串寫入到blob 字段中並 同步到數據庫
4 、讀出Blob 字段的數據
public NewsEntry loadNews(long id) throws Exception {
NewsEntry entry = this.getNewsFromDB(id);
StringBuffer sb = new StringBuffer();
// 這個是blob類型的代碼
byte[] content = new byte[1];
if (entry != null) {
Blob contents2 = entry.getContents2();
if (contents2 != null) {
int len = (int) contents2.length();
content = new byte[len];
InputStream input = contents2.getBinaryStream();
input.read(content,0,len);
}
}
return entry;
}