说下关于映射大对象(Blob,Clob)数据类型在Oracle中的处理....希望对大家有所帮助
首先先介绍下开发环境服务器软件:Tomcat 5.0
IDE工具:Eclipse3.2+MyEclipse5.1.0GA 插件
DataBase:Oracle9i
JDK:1.5版
还有就是开源框架Hibernate 3.0
前两天在家看了看<<深入浅出 Hibernate>>,里面介绍有关于Hibernate映射大对象数据类型的介绍,因此今天发表这篇文章希望对大家有所帮助,至于在MySql,MS SQLServer中如何映射,就不用说了,因为比较简单,网站上也有很多相关资料可以查看,不多说了,言归正传吧.
数据库结构:
字段名 | 数据类型 | 约束条件 |
ID | NUMBER(10) | PK |
NAME | VARCAHR2(30) | NOT NULL |
IMAGE | Blob | |
DISCRIPTION | Clob |
类名(pojo)TUser,映射文件TUser.hbm.xml省略.
代码如下:
public void saveTUser()throws Exception
{
Session session = null;
Transaction tran = null;
try
{
session = sessionFactory.openSession();
tran = session.beginTransaction();
TUser user = new TUser();
user.setName("zhangsan");
user.setImage(Hibernate.createBlob(new byte[1]));
user.setDiscription(Hibernate.createClob(" "));
session.save(user);
session.flush();
session.refresh(user,LockMode.UPGRADE);
oracle.sql.BLOB blob = (oracle.sql.BLOB)user.getImage();
OutputStream outs = blob .getBinaryOutputStream();
FileInputStream file = new FileInputStream("c://1.jpg");
byte[] bytes = new byte[10240];
int len;
while((len=file.read(bytes))!=-1)
{
outs.write(bytes,0,len);
}
file.close();
outs.close();
oracle.sql.CLOB clob = (oracle.sql.CLOB)user.getDiscription();
java.io.Writer writer = clob.getCharacterOutputStream();
writer.write("Hello,World......");
writer.close();
session.save(user);
tran.commit();
}catch(HibernateException e){
e.printStackTrace();
tran.rollback();
}finally{
session.close();
}
}
以上代码在Hibernate3.0以前,能运行,但是我的Hibernate是3.0的,所以运行时候有异常{
Session session = null;
Transaction tran = null;
try
{
session = sessionFactory.openSession();
tran = session.beginTransaction();
TUser user = new TUser();
user.setName("zhangsan");
user.setImage(Hibernate.createBlob(new byte[1]));
user.setDiscription(Hibernate.createClob(" "));
session.save(user);
session.flush();
session.refresh(user,LockMode.UPGRADE);
oracle.sql.BLOB blob = (oracle.sql.BLOB)user.getImage();
OutputStream outs = blob .getBinaryOutputStream();
FileInputStream file = new FileInputStream("c://1.jpg");
byte[] bytes = new byte[10240];
int len;
while((len=file.read(bytes))!=-1)
{
outs.write(bytes,0,len);
}
file.close();
outs.close();
oracle.sql.CLOB clob = (oracle.sql.CLOB)user.getDiscription();
java.io.Writer writer = clob.getCharacterOutputStream();
writer.write("Hello,World......");
writer.close();
session.save(user);
tran.commit();
}catch(HibernateException e){
e.printStackTrace();
tran.rollback();
}finally{
session.close();
}
}
Exception in thread "main" java.lang.ClassCastException: org.hibernate.lob.SerializableBlob
要使以上代码在Hibernate3.0中运行起来,需对以上代码进行修改,上面红色部分代码修改为:
SerializableBlob blob = (SerializableBlob)user.getImage();
java.sql.Blob blo = (java.sql.Blob)blob.getWrappedBlob();
oracle.sql.BLOB obj = (oracle.sql.BLOB)bol;
OutputStream outs = obj.getBinaryOutputStream();
至于下面Clob的操作我就不多说了,嘿嘿,相信以您的聪明才智,一定知道该怎么改了.
在学习开源的一些框架的时候,千万注意版本与版本之间的区别,以免在开发过程中走弯路,呵呵
大家如果有兴趣的话也可以做下看看啊,祝好运咯...........
当然,以上代码或许有什么地方有问题,我也不知道...哈哈(^_^,猜测哈...)