textarea的内容保留到blob,然后读到textarea中显示出来

textarea的内容保存到blob,然后读到textarea中显示出来
以下包括从网络上获取的内容和自己的一些理解,
可能存在不正确的地方,如遇到请指出,谢谢。

----------------------------SEPARATE-LINE----------------------------

万物起因

不允许的操作: streams type cannot be used in batching

operation not allowed: streams type cannot be used in batching



场景

Hibernate 2.1.4
将textarea中的值保存到Oracle的blob中,然后将blob保存的值显示在textarea中
http://www.iteye.com/problems/27144
当字节数超过一定大小时则出现如上的异常

BLOB指oracle.sql.BLOB,实现了java.sql.Blob
BlobImpl指hibernate.lob.BlobImpl,同样实现了java.sql.Blob

网上很多人都说将Hibernate的参数jdbc.batch_size的值设置为0即可解决问题
但我没有这么做
于是开始寻找解决办法
经典老帖"使用JDBC和Hibernate来写入Blob型数据到Oracle中":http://www.iteye.com/topic/254

我的想法一般都比较简单string2blob和blob2string就应该能解决问题
这其中要通过字节数组byte[]来过渡

于是想应该将Blob转成BLOB然后通过getBytes方法就可以拿到bytes
blob强转为BLOB报ClassCastException
Debug一看原来运行中的Blob是BlobImpl类型的
强转为BLOB当然产生ClassCastException

既然发现运行中的类型为BlobImpl,所以强转
因为看起来BlobImpl也有getBytes方法
if (true == blob instanceof BlobImpl) {
	BlobImpl bb = (BlobImpl) blob;
	bytes = bb.getBytes(0, (int) bb.length());
}

但无法调用BlobImpl.getBytes方法,出现如下异常
java.lang.UnsupportedOperationException: Blob may not be manipulated from creating session

还是Google
原来Blob类型的只能用两个方法
https://forum.hibernate.org/viewtopic.php?t=933977
引用
As u can see out of the sourcecode, every method do nothing but:
Code:
throw new UnsupportedOperationException("Blob may not be manipulated from creating session");

The only to methods who are implemented really, are:
getBinaryStream()

length()


So use those instead of getBytes()

Why they used the text "Blob may not be manipulated" i can't say...
Maybe anybody can help us with that?

Greets


于是继续改代码

public static byte[] getBytes(Blob blob) throws SerialException,
		IOException, SQLException {
	if (null == blob || true != blob instanceof Blob)
		throw new IllegalArgumentException("LOBUtil.getBytes方法无法接受你传入的参数:"
				+ blob);
	byte[] bytes = null;
	if (true == blob instanceof BlobImpl) {
		InputStream is = blob.getBinaryStream();
		bytes = IOUtil.newInstance().getBytes(is);
	} else if (true == blob instanceof BLOB) {
		bytes = ((BLOB) blob).getBytes();
	}
	return bytes;
}


这样就应该没啥大问题了





1 楼 lszwycn 2009-10-22  
hibernate 3.5中实现了两个新的类型text, image, 当前还没有release,可以看看svn中的代码
2 楼 ltl3884 2009-10-22  
lszwycn 写道
hibernate 3.5中实现了两个新的类型text, image, 当前还没有release,可以看看svn中的代码



test111
3 楼 jasonshi 2010-02-20  
textarea的话,用clob比blob要好。
如果是oracle数据库,在最新jdbc driver下,可以直接用string的方式去访问clob字段,没有差别的。

最好将blob/clob独立成一个表,其他表需要的是否放一个clob/blob表的id,这样只需要在一个地方处理clob/clob的问题,lob数据大时,也可以用到一些lazy load的优化
4 楼 lucane 2010-07-09  
确实是应当把clob或blob分离出来,但是因为历史遗留项目,所以hbt版本这些东西都定死了