Hibernate BloB 字段SQLSever/Oracle读写比较
特别感谢:zhaof <zhaof@shineenergy.com>提供。
1\Oracle
配置文件
<class name ="com......TUser" table="T_USER">
<pro ......./>
<property
name="image"
column="resume"
type="java.sql.Blob"
/>
<property
name="resume"
column="resume"
type="java.sql.Clob"
/>
</class>
程序
PrepareStaement preStmt =
dbconn.prepareStatement("insert into TUSER(name,image,resume) values
("?,?,?")");
//写
preStmt.setString(1,"Shark");
/*重点要先插空的Blob和CLob字段*/
preStmt.setString(2,oracle.sql.BLOB.empty_lob());
preStmt.setString(3,oracle.sql.CLOB.empty_lob());
preStme.executeUpdate();
preStme.close();
preStmt = dbconn.prepareStatement("select name ,image,resume
from T_USER where name=? for update");
preStmt.setString(1,"Shark");
Result rset= prsStmt.executQuery();
rset.next();
oracle.sql.Blob imgBlob = (oracle.sql.BLOB) rset.getBlob(1);
oracle.sql.Clob resClob = (oracle.sql.CLOB) rset.getClob(2);
FileInputStream inStream = new FileInputStream ("c:\\inimage.jpg");
FileInputStream outStream = imgBlob.getBinaryOutputStream();
byte[] buf new byte[10240];
int len;
while((len=inStream.read(bu))>0){
outStream.write(buf,0.len);
}
outStream.close();
inStream.close();
resClob.putString(1,"This is my clob");
preStmt = dbconn.prepareStatment("upate T_USER set image=?,resume=? where name=?")
preStmt.setBlob(1,imgBlob);
preStmt.setClob(2,resClob);
preStmt.setString(3,"Shark");
preStmt.exeuteUpdate();
preStmt.close();
dbconn.commit();
dbconn.close();
2\SQLServer
配置文件
<class name ="com......TUser" table="T_USER">
<property
name="image"
column="resume"
type="java.sql.Blob"
/>
<property
name="resume"
column="resume"
type="java.sql.Clob"
/>
</class>
程序
FileInputStream imgis = new FileInputStream("c:\\inimage.jpg");
//写
Blob img=Hibernate.createBlob(img);
user.setImage(img);
Clob resume=Hibernate.createBlob("This is Clob");
user.setResume(resume);
Transaction tx=session.beginTransaction();
session.save(user);
tx.commit();
//读
InputStream is=img.getBnayStream();
FileOutputStream os= new FileOutpurStream("c:\\outimage.jpg");
byte[] buf =new byte[102400];
int len;
while((len=is.read.(buf)!=-1))
{fos.write(buf,0,len);}
fos.close();
is.close