蓝色天空

走在IT的路上,随时需要抬头看看天空
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

java保存blob字段到数据库

Posted on 2012-07-29 11:18  my_house_station  阅读(1643)  评论(0编辑  收藏  举报

持久类定义字段: private Blob diff;

设置要保存的对象:

public Blob getBlob(Object o) {
  ByteArrayOutputStream outs = new ByteArrayOutputStream();
  try {
   ObjectOutputStream oos = new ObjectOutputStream(outs);
   oos.writeObject(o);
  } catch (IOException e) {
   throw new RuntimeException(e);
  }
  return (Hibernate.createBlob(outs.toByteArray()));
 }

 

从数据库中取出要对象:

diff=rs.getBlob("content")

将blob字段转换成对象:

 // 从申请单中取出对象
 public Object getObject() {
  Object obj = null;
   try {
    ObjectInputStream ois = new ObjectInputStream(diff.getBinaryStream());
    obj = (Object) ois.readObject();
   } catch (SQLException e) {
    e.printStackTrace();
   } catch (IOException e) {
    throw new RuntimeException(e);
   } catch (ClassNotFoundException e) {
    e.printStackTrace();
   }
  return obj;