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