解析應用jdbc,hibernate處置clob/blob字段的詳解。本站提示廣大學習愛好者:(解析應用jdbc,hibernate處置clob/blob字段的詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是解析應用jdbc,hibernate處置clob/blob字段的詳解正文
(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();