Some print.
Some print.
~SingleForum~无废话记录~ + ~19~记录点有用的好吗?少说废话少装b~

~SingleForum~无废话记录~ » java

Hibernate操作BLOB

Started 8 months ago by admin. | Tags: . . .

这是Cat对象定义
  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;}
  }

  这是Cat.hbm.xml

  <?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了:

  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);
   out.write(data);
   fin.close();
   out.close();
   s.flush();
   tx.commit();
  } catch (Exception e) {
   System.out.println(e.getMessage());
  } finally {
   if (s != null)
   try {
    s.close();
   } catch (Exception e) {}
  }
  }
  }

RSS feed for this topic