hibernate版本从Oracle中读取Blob数据

转自:https://blog.csdn.net/qq_34239028/article/details/81293252

  1. hibernate3.2是采用的SerializableBlob类来处理Blob对象的。

public byte[] getPic(String isbn) throws Exception {
	byte[] pic = null;
	String sql = "select pic from tbook where isbn = ?";
	this.openConnection();
	SQLQuery q = this.session.createSQLQuery(sql);
	q.setString(0, isbn);
	Iterator it = q.list().iterator();
	while(it.hasNext()){
		Object obj=it.next();
		SerializableBlob blob= (SerializableBlob)obj;
		pic=blob.getBytes(1, (int)blob.length());
		
	}
	return pic;
}
  1. 在Hibernate3.5之后去掉了SerializableBlob这个类,但同时又增加了SerializableBlobProxy来处理Blob字段值。Blob字段是Hibernate返回的Blob对象实际上是代理类SerializableBlobProxy的实例,提供了java.sql.Blob接口定义的方法(通过反射的方式)
    注意:不能把这个实例转换成oracle.sql.Blob类型,会发生类型转换异常(java.lang.ClassCastException),提供信息为cannot be cast to oracle.sql.BLOB
public byte[] getPic(String isbn) throws Exception {
	byte[] pic = null;
	
	String sql = "select pic from tbook where isbn = ?";
	this.openConnection();
	SQLQuery q = this.session.createSQLQuery(sql);
	q.setString(0, isbn);
	Iterator it = q.list().iterator();
	while(it.hasNext()){
		Object obj=it.next();
		SerializableBlobProxy proxy=(SerializableBlobProxy)Proxy.getInvocationHandler(obj);
		java.sql.Blob blob = proxy.getWrappedBlob();
		pic=blob.getBytes(1, (int)blob.length());
	}
	return pic;
}

你可能感兴趣的:(hibernate)