JDBC+Hibernate將Blob資料寫入Oracle

來源:互聯網
上載者:User
 Oracle的Blob欄位比較特殊,他比long欄位的效能要好很多,可以用來儲存例片之類的位元據。

  寫入Blob欄位和寫入其它類型欄位的方式非常不同,因為Blob自身有一個cursor,你必須使用cursor對blob進行操作,因而你在寫入Blob之前,必須獲得cursor才能進行寫入,那麼如何獲得Blob的cursor呢?

  這需要你先插入一個empty的blob,這將建立一個blob的cursor,然後你再把這個empty的blob的cursor用select查詢出來,這樣通過兩步操作,你就獲得了blob的cursor,可以真正的寫入blob資料了。

  看下面的JDBC的demo,把oraclejdbc.jar這個二進位檔案寫入資料庫表javatest的content欄位(這是一個blob型欄位)

import java.sql.*;
import java.io.*;
import oracle.sql.*;
public class WriteBlob {

public static void main(String[] args) {

 try {
  DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
  Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","fankai","fankai");
  conn.setAutoCommit(false);

  BLOB blob = null;

  PreparedStatement pstmt = conn.prepareStatement("insert into javatest(name,content) values(?,empty_blob())");
  pstmt.setString(1,"fankai");
  pstmt.executeUpdate();
  pstmt.close();

  pstmt = conn.prepareStatement("select content from javatest where name= ? for update");
  pstmt.setString(1,"fankai");
  ResultSet rset = pstmt.executeQuery();
  if (rset.next()) blob = (BLOB) rset.getBlob(1);

  String fileName = "oraclejdbc.jar";
  File f = new File(fileName);
  FileInputStream fin = new FileInputStream(f);
  System.out.println("file size = " + fin.available());

  pstmt = conn.prepareStatement("update javatest set content=? where name=?");

  OutputStream out = blob.getBinaryOutputStream();

  int count = -1, total = 0;
  byte[] data = new byte[(int)fin.available()];
  fin.read(data);
  out.write(data);
  /*
  byte[] data = new byte[blob.getBufferSize()]; 另一種實現方法,節省記憶體
  while ((count = fin.read(data)) != -1) {
   total += count;
   out.write(data, 0, count);
  }
  */

  fin.close();
  out.close();

  pstmt.setBlob(1,blob);
  pstmt.setString(2,"fankai");

  pstmt.executeUpdate();
  pstmt.close();

  conn.commit();
  conn.close();
 } catch (SQLException e) {
   System.err.println(e.getMessage());
  e.printStackTrace();
 } catch (IOException e) {
  System.err.println(e.getMessage());
 }
}

}

  仔細看上例,分三步:

  1、插入空blob

into javatest(name,content) values(?,empty_blob());

  2、獲得blob的cursor

select content from javatest where name= ? for update;

  注意!!!必須加for update,這將鎖定該行,直至該行被修改完畢,保證不產生並發衝突。

  3、update javatest set content=? where name=

  用cursor往資料庫寫資料

  這裡面還有一點要提醒大家:

  JDK1.3帶的JDBC2.0規範是不完善的,只有讀Blob的介面,而沒有寫Blob的介面,JDK1.4帶的JDBC3.0加入了寫Blob的介面。你可以使用JDBC3.0的介面,也可以直接使用Oracle的JDBC的API,我在上例中使用了Oracle的JDBC的API。

  另外要注意的是:

java.sql.Blob

oracle.sql.BLOB

  注意看blob的大小寫,是不一樣的。寫程式的時候不要搞混了。

  下面看看用Hibernate怎麼寫,原理是一樣的,也要分三步,但是代碼簡單很多

  這是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) {}
  }
 }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.