hibernate对Blob类型字段进行数据添加

    技术2024-12-21  4

    对于MS SQL和MYSQL数据库,操作Blob字段很简单,而对于oracle数据进行操作,则要复杂些,这是因为oracle访问Blob和Clob有它独特的方式,oracle Blob/Clob字段本身有一个游标(cursor),必须要通过这个游标对Blob/Clob进行操作,在Blob/Clob未创建前,我们无法获得它们的游标句柄,因此,我们必须先得创建一个空的Blob/Clob字段值,然后再从这个空的字段值取得游标句柄,再来进行我们的操作.前面那篇文章的操作方式就是这样的,不是很清楚的,可以结合以前的那篇来看,Blob和Clob的操作方式大体上相同.

    hbm.xml

    <?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="hibernate.Blobtest" table="blobtest" catalog="hbtplis">        <id name="id" type="java.lang.Long">            <column name="id" />            <generator class="native" />        </id>        <property name="images" type="java.sql.Blob">            <column name="images" />        </property>        <property name="name" type="java.lang.String">            <column name="name" />        </property>    </class></hibernate-mapping>

    pojo:

    package hibernate;

    import java.sql.Blob;

    /*** * @author coffee*/

    public class Blobtest implements java.io.Serializable {

    private Long id;private Blob images;private String name;

    public Blobtest() {}

    public Blobtest(Blob images, String name) {   this.images = images;   this.name = name;}

    public Long getId() {   return this.id;}

    public void setId(Long id) {   this.id = id;}

    public Blob getImages() {   return this.images;}

    public void setImages(Blob images) {   this.images = images;}

    public String getName() {   return this.name;}

    public void setName(String name) {   this.name = name;}

    }

    DAO:

    package hibernate;

    import java.io.FileOutputStream;import java.io.InputStream;import java.sql.Blob;import org.hibernate.Hibernate;import org.hibernate.LockMode;import org.hibernate.Transaction;

    /*** * @author coffee*/

    public class BlobtestDAO extends BaseHibernateDAO {

    public void save(Blobtest blobtest) throws Exception {   try {    /*    * 第一种方式,可用于ms sql和mysql数据库    Transaction tran=getSession().beginTransaction();    FileInputStream img = new FileInputStream("d://movie//linux4.jpg");    Blob images = (Blob) Hibernate.createBlob(img);    blobtest.setImages(images);    getSession().save(blobtest);    tran.commit();    */    //对于oracle这样的数据库不能以第一种方式那样,必须向下面这样操作    Transaction tran=getSession().beginTransaction();    blobtest.setImages(Hibernate.createBlob(new byte[1]));    getSession().save(blobtest);    getSession().flush();    getSession().refresh(blobtest,LockMode.UPGRADE);    Blob blob=blobtest.getImages();    InputStream is=blob.getBinaryStream();    FileOutputStream fos=new FileOutputStream("d://pic//linux4.jpg");    byte[] buf=new byte[102400];    int len;    while((len=is.read(buf))!=-1){     fos.write(buf,0,len);    }    fos.close();    is.close();    getSession().save(blobtest);     tran.commit();   } catch (RuntimeException re) {    throw re;   }}}

    最新回复(0)