Hibernate操作Blob資料,hibernateblob資料

來源:互聯網
上載者:User

Hibernate操作Blob資料,hibernateblob資料

 


首先看資料庫,資料庫中建立一個BlobTable表,表中有兩個欄位,一個id(主鍵)一個picture欄位是Blob類型欄位。然後使用Hibernate向該資料庫中寫入和讀取資料

在POJO類中picture屬性用的是Blob類型資料。

下面看操作源碼

package dao;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.math.BigDecimal;import java.sql.Blob;import org.hibernate.LobHelper;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import Factory.HibernateSessionFactory;import entity.Blobtable;public class BlobDao {private Session session = null;private Transaction tran = null;public BlobDao(){this.session = HibernateSessionFactory.getSession();}public void saveBlob(Blobtable bigdate,String path) throws IOException{/*InputStream in = this.getClass().getResourceAsStream(path);byte[] bytes = new byte[in.available()];in.read(bytes);in.close();*/File file = new File(path);FileInputStream fis = new FileInputStream(file);byte[] bytes = new byte[fis.available()];fis.read(bytes);LobHelper lh = session.getLobHelper();bigdate.setPicture(lh.createBlob(bytes));tran = session.beginTransaction();try{session.save(bigdate);tran.commit();System.out.println("插入成功!");}catch(Exception e){System.out.println("插入失敗!");tran.rollback();}finally{HibernateSessionFactory.closeSession();fis.close();}}public void getBlob(BigDecimal id,String targetpath) throws Exception{String hql = "From Blobtable where id = ?";Query query = session.createQuery(hql);query.setBigDecimal(0, id);Blobtable bt = (Blobtable) query.uniqueResult();Blob image = bt.getPicture();InputStream in = image.getBinaryStream();OutputStream os = new FileOutputStream(targetpath);int n = -1;while((n=in.read())!=-1){os.write(n);}in.close();os.close();}}
package Test;import java.io.IOException;import java.math.BigDecimal;import dao.BlobDao;import entity.Blobtable;public class Test {public static void main(String[] args) {BlobDao bb = new BlobDao();Blobtable bt = new Blobtable();bt.setId(new BigDecimal(5));try {String path = "f:\\a.jpg";bb.saveBlob(bt, path);} catch (IOException e) {e.printStackTrace();}BlobDao bd = new BlobDao();try {bd.getBlob(new BigDecimal(1), "e:\\a.jpg");System.out.println("寫出成功!");} catch (Exception e) {e.printStackTrace();}}}



 


hibernate怎儲存blob資料

java.sql.Blob n=Hibernate.createBlob(bytes);
你可以參考下下面這個例子,應該對你有很大協助
developer.51cto.com/art/200906/130231.htm
 
JAVA新手助,對於Hibernate操作Blob

這種情況,建議你換個oracle驅動包,盡量換個最新的。
希望對你有協助。
 

相關文章

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.