码迷,mamicode.com
首页 > 系统相关 > 详细

Hibernate操作Blob数据

时间:2014-09-19 15:41:45      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:hibernate   blob   

 


首先看数据库,数据库中新建一个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数据

标签:hibernate   blob   

原文地址:http://blog.csdn.net/u011740475/article/details/39397741

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!