java保存blob字段到数据库

持久类定义字段: 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;

原文地址:https://www.cnblogs.com/wjlstation/p/2613889.html