首先看數據庫。數據庫中新建一個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(); } } }