的接口,而没有写Blob的接口,JDK1.4带的JDBC3.0加入了写Blob的接口。你可以使用JDBC3.0的接口,也可以直接使用Oracle的JDBC的API,我在上例中使用了Oracle的JDBC的API。
另外要注意的是:
java.sql.Blob
oracle.sql.BLOB
注意看blob的大小写,是不一样的。写程序的时候不要搞混了。
下面看看用Hibernate怎么写,原理是一样的,也要分三步,但是代码简单很多
这是Cat对象定义
java代码:
package com.fankai;
import java.sql.Blob;
public class Cat {
private String id;
private String name;
private char sex;
private float weight;
private Blob image;
public Cat() { }
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public char getSex() { return sex; }
public void setSex(char sex) { this.sex = sex; }
public float getWeight() { return weight; }
public void setWeight(float weight) { this.weight = weight; }
public Blob getImage() { return image; }
public void setImage(Blob image) { this.image = image;}
}
使用JDBC和Hibernate来写入Blob型数据到Oracle中(3)
时间:2011-07-28
这是Cat.hbm.xml
java代码:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="com.fankai.Cat" table="cat">
<!--jcs-cache usage="read-only"/-->
<id name="id" unsaved-value="null">
<generator class="uuid.hex"/>
</id>
<property name="name" length="16" not-null="true"/>
<property name="sex" length="1" not-null="true"/>
<property name="weight" />
<property name="image" />
</class>
</hibernate-mapping>
下面是完整的用Hibernate写入Blob的例子,相比JDBC,已经简单轻松多了,也不用写那些Oracle特殊的sql了:
java代码:
package com.fankai;
import java.sql.Blob;
import net.sf.hibernate.*;
import oracle.sql.*;
import java.io.*;
public class TestCatHibernate {
public static void testBlob() {
Session s = null;
byte[] buffer = new byte[1];
buffer[0] = 1;
try {
SessionFactory sf = HibernateSessionFactory.getSessionFactory();
s = sf.openSession();
Transaction tx = s.beginTransaction();
Cat c = new Cat();
c.setName("Robbin");
c.setImage(Hibernate.createBlob(buffer));
s.save(c);
s.flush();
s.refresh(c, LockMode.UPGRADE);
BLOB blob = (BLOB) c.getImage();
OutputStream out = blob.getBinaryOutputStream();
String fileName = "oraclejdbc.jar";
File f = new File(fileName);
FileInputStream fin = new FileInputStream(f);
int count = -1, total = 0;
byte[] data = new byte[(int)fin.available()];
fin.read(data);
|