<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
....
<property name="hibernate.jdbc.batch_size">0</property>
<mapping resource="onlyfun/caterpillar/File.hbm.xml"/>
</session-factory>
</hibernate-configuration>
CREATE TABLE t_file ( id INTEGER NOT NULL, des CLOB, image BLOB );假设FILE类别设定如下:
package onlyfun.caterpillar;
import java.sql.Blob;
import java.sql.Clob;
public class File {
private Integer id;
private Clob des;
private Blob image;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Clob getDes() {
return des;
}
public void setDes(Clob des) {
this.des = des;
}
public Blob getImage() {
return image;
}
public void setImage(Blob image) {
this.image = image;
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="onlyfun.caterpillar.File" table="t_file">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="des" column="des"/>
<property name="image" column="image"/>
</class>
</hibernate-mapping>
package onlyfun.caterpillar;更多其它在Oracle中的解决方案,您可以参考 Using Clobs/Blobs with Oracle and Hibernate
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import org.hibernate.Hibernate;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class BlobClobDemo {
public static void main(String[] args) throws IOException, SQLException {
// Configuration 负责管理 Hibernate 配置讯息
Configuration config = new Configuration().configure();
// 根据 config 建立 SessionFactory
// SessionFactory 将用于建立 Session
SessionFactory sessionFactory = config.buildSessionFactory();
File file = new File();
// 先建立空的字段
file.setDes(Hibernate.createClob(" "));
file.setImage(Hibernate.createBlob(new byte[1]));
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(file);
// 执行flush,让Hibernate INSERT 空字段
session.flush();
// 执行refresh,让Hibernate执行SELECT FOR UPDATE
session.refresh(file, LockMode.UPGRADE);
FileInputStream fileInputStream = new FileInputStream("c:\\workspace\\Wind.bmp");
// 重新设定真正要写入的Blob/Clob数据
file.setDes(Hibernate.createClob("...blah...blah..."));
file.setImage(Hibernate.createBlob(fileInputStream));
// 再次save
session.save(file);
tx.commit();
session.close();
fileInputStream.close();
sessionFactory.close();
}
}