(1)不同數(shù)據(jù)庫(kù)中對(duì)應(yīng)clob,blob的類(lèi)型:
mysql中 : clob對(duì)應(yīng)text blob對(duì)應(yīng)blob
db2/oracle中 clob對(duì)應(yīng)clob blob對(duì)應(yīng)blob
(2)domain中對(duì)應(yīng)類(lèi)型:
clob 對(duì)應(yīng) String blob 對(duì)應(yīng) byte[]
clob 對(duì)慶 java.sql.Clob blob 對(duì)應(yīng) java.sql.Blob
(3)hibernate配置文件中對(duì)應(yīng)類(lèi)型:
clob > clob blob > binay
也可以直接使用數(shù)據(jù)庫(kù)提供類(lèi)型,例如:oracle.sql.Clob,oracle.sql.Blob。
2、jdbc操作clob (以oracle為例)
首先操作clob/blob不像操作varchar類(lèi)型那樣簡(jiǎn)單,插入步驟一般為兩步:第一步插入一個(gè)空值,第二步鎖住此行,更新clob/blob字段.
//插入空值
conn.setAutoCommit(false);
String sql = "insert into file(name,file_content) values("jack",EMPTY_CLOB());
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.executeUpdate();
//鎖住此行
String sql = "select file_content from file where name='jack' for update";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
oracle.sql.Clob clob = (oracle.sql.Clob)rs.getClob(1);
java.io.OutputStream writer = clob.getAsciiOutputStream();
byte[] temp = newFileContent.getBytes();
writer.write(temp);
writer.flush();
writer.close();
//
pstmt.close();
讀取內(nèi)容:
oracle.sql.Clob clob = rs.getClob("file_content");
if(null!=clob)
{
Reader is = clob.getCharacterStream();
BufferedReader br = new BufferedReader(is);
String s = br.readLine();
while (s != null)
{
content += s + "<br>";
s = br.readLine();
}
}
3、jdbc操作blob
conn.setAutoCommit(false);
String sql = "insert into photo(name,photo) values("jack",empty_blob());
pstmt = conn.prepareStatement(sql);
pstmt = conn.executeUpdate();
//
sql = "select photo from photo where name='jack'";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery(sql);
if(rs.next())
oracle.sql.Blob blob = (oracle.sql.Blob)rs.getBlob(1);
//write to a file
File file = new File("c:\\test.rar");
FileInputStream fin = new FileInputStream(file);
OutputStream out = blob.getBinaryOutputStream();
int count = -1, total = 0;
byte[] data = new Byte[blob.getBufferSize()];
while ((count = fin.read(data)) != -1)
{
total += count;
out.write(data, 0, count);
}
4、hibernateth處理clob
MyFile file = new Myfile();
file.setName("jack");
file.setContent(hibernate.createClob(""));
session.save(file);
session.flush();
session.refresh(file,LockMode.UPGRADE);
oracle.sql.Clob clob = (oracle.sql.Clob)file.getContent();
Writer pw = clob.getCharacterOutputStream();
pw.write(longText);//寫(xiě)入長(zhǎng)文本
pw.close();
session.close();
5、使用hibernate處理blob:
原理基本相同:
Photo photo = new Photo();
photo.setName("jack");
photo.setPhoto(hibernate.createBlob(""))://放一個(gè)空值
session.save(photo);
session.flush();
//
session.refresh(photo,LockMode.UPGRADE); //鎖住此對(duì)象
oracle.sql.Blob blob = photo.getPhoto();//取得此blob的指針
OutputStream out = blob.getBinaryOutputStream();
//寫(xiě)入一個(gè)文件
File f = new File("c:\\test.rar");
FileInputStream fin = new FileInputStream(f);
int count = -1, total = 0;
byte[] data = new byte[(int)fin.available()];
out.write(data);
fin.close();
out.close();
session.flush();