(1)不同數據庫中對應clob,blob的類型:
mysql中 : clob對應text blob對應blob
db2/oracle中 clob對應clob blob對應blob
(2)domain中對應類型:
clob 對應 String blob 對應 byte[]
clob 對慶 java.sql.Clob blob 對應 java.sql.Blob
(3)hibernate配置文件中對應類型:
clob > clob blob > binay
也可以直接使用數據庫提供類型,例如:oracle.sql.Clob,oracle.sql.Blob。
2、jdbc操作clob (以oracle為例)
首先操作clob/blob不像操作varchar類型那樣簡單,插入步驟一般為兩步:第一步插入一個空值,第二步鎖住此行,更新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();
讀取內容:
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);//寫入長文本
pw.close();
session.close();
5、使用hibernate處理blob:
代碼如下:
原理基本相同:
Photo photo = new Photo();
photo.setName("jack");
photo.setPhoto(hibernate.createBlob(""))://放一個空值
session.save(photo);
session.flush();
//
session.refresh(photo,LockMode.UPGRADE); //鎖住此對象
oracle.sql.Blob blob = photo.getPhoto();//取得此blob的指針
OutputStream out = blob.getBinaryOutputStream();
//寫入一個文件
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();