现在的位置: 首页 > 综合 > 正文

java中用Blob的数据类型向数据库插入图片

2013年09月16日 ⁄ 综合 ⁄ 共 2440字 ⁄ 字号 评论关闭

package com.vnet.flyed.text;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.List;

import oracle.sql.BLOB;

import org.hibernate.Hibernate;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.lob.SerializableBlob;

import com.vnet.flyed.factory.HibernateSessionFactory;
import com.vnet.flyed.pojo.Vnetuser;

public class HibernateTest {
 public static void main(String[] args) {
  
  Configuration config = new Configuration().configure();
  Session session = HibernateSessionFactory.getSession();
  Vnetuser user = new Vnetuser();
  Transaction tr = session.beginTransaction();
  user.setId(100);
  user.setName("flyed");
  user.setPassword("flyed");
  try {
   user.setImage(oracle.sql.BLOB.empty_lob());
  } catch (SQLException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  
  user.setResume(Hibernate.createClob(""));
  session.save(user);
  session.flush();
  try {
   session.refresh(user, LockMode.UPGRADE);
   SerializableBlob sb = (SerializableBlob) user.getImage();
   // 需要调用它的getWrappedBlob来转型
   BLOB blob = (BLOB) sb.getWrappedBlob();
   // 将某个问件读入后,写到Blob字段的输出流中
   OutputStream out = blob.getBinaryOutputStream();
   FileInputStream imgis = new FileInputStream("d:/tom.gif");
   byte[] buf = new byte[102400]; // 10k缓存
   int len;
   while ((len = imgis.read(buf)) > 0) {
    out.write(buf, 0, len);
   }
   imgis.close();
   out.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  session.save(user);
  tr.commit();
  
  String hql = "from Vnetuser where id=100";
  Query query = session.createQuery(hql);
  List list = query.list();
  if (list.size() > 0) {
   Vnetuser user1 = (Vnetuser) list.get(0);
   try {
    InputStream is = user1.getImage().getBinaryStream();
    OutputStream os = new FileOutputStream("d:/a.jpg");
    byte[] buf = new byte[1024];
    int i = 0;
    while ((i = is.read(buf)) != -1) {
     os.write(buf, 0, i);
    }

   } catch (SQLException e) {   
    e.printStackTrace();
   } catch (FileNotFoundException e) { 
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  session.close();
 }
}

抱歉!评论已关闭.