Hibernate操作Blob資料

來源:互聯網
上載者:User

標籤:out   插入   cto   ssi   code   test   cep   puts   ima   

 


首先看資料庫。資料庫中建立一個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資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.