ITeye博客

hibernate 操作clob,blob对象

friping · 2009-05-21 14:39 · hibernate · Weblogic · SQL · JDBC · Hibernate · Oracle · Markdown

转自:http://hpingliu.blog.ccidnet.com/blog-htm-do-showone-type-blog-itemid-144245-uid-48802.html]

作为测试,我们新建一个TUser对象,其image属性中,保存了一个图片文件的二进制内容。而其resume属性,我们以一个简单的字符串作为填充。

1 TUser user = new TUser();
2
3 user.setAge( new Integer( 20 ));
4
5 user.setName( " Shark " );
6
7 FilelnputStream imgis = new FileinputStream( " C:\\inimage.jpg "
8
9 Blob img = Hibernate.createBlob(imgis);
10
11 user.setlmage(img);
12
13 Clob resume = Hibernate.createClob( " This is Clob " );
14
15 user. setResume(resume);
16
17 Transaction tx = session.beginTransaction();
18
19 session.save(user);
20
21 tx.commit();
22
23

上面的代码中,我们通过Hibemate.createBlob和Hibemate.createClob创建了对应的Blob和Clob对象。其中Blob对象基于一个FileInputStream构建,而Clob对象基于一个字符串构建。

完成了写入操作,对应的读取操作代码如下:

1 // 假设库表记录的id字段等于3
2 TUser user = (TUser) session.load(TUger.elaa., load(TUser. class , new Integer( 3 ));
3 Clob resume = user.getResume();
4 // 通过Clob.getSubString()方法获取Clob字段内容
5 System.out.println( " User resume=> " + resume.getSubString( 1 ,( int )resume.length()));
6 Blob img = user.getImage();
7 // 通过Blob.getBinaryS=ream()方法获取二进制流
8 InputStream is = img.getBinaryStream();
9 FileOutputStream fos = new FileOutputStream( " C:\\outimage.jpg " );
10 byte [] buf = new byte ( 102400 );
11 int len;
12 while ((len = is.read(buf)) !=- 1 ) {
13 fos.write(buf, 0 ,len);
14 }
15 fos.close();
16 is.close();
17
18


通过上面的代码,我们完成了针对SQLServer的Blob/Clob型字段操作.看起来非常简单,不过,并非侮种数据库都如此友善。让我们接着来看看Oracle数据库下的Blob/Clob字段读写,
通过修改hibernate.cfg.xml中的Dialect配置完成数据库切换后,我们再次运行上面的TUser对象保存例程。
程序运行期间抛出异常:

Hibernate:select hibernate_sequence.nextval from dual
Hibernate:insert into T_USER (name, age, image,resume. id) values(?, ?, ?, ?, ?)
17:27:24,161 ERROR JDBCExceptionReporter:58 - - 不允许的操作: Streams type cannot be used in batching
17:27:24,171 ERROR Sessionlmpl:2399 - Could not synchronize database state with session
net.sf.hibernate.exception.GenericJDBCException:could not insert:[com.redsaga.hibernate.db.entity.TUser#6]
...


观察异常信息:streams type cannot be used in batching.这意味着Oracle JDBC不允许流操作以批量方式执行(Oracle CLOB采用流机制作为数据读写方式)。
这种错误一般发生在hibernate.cfg.xml中的hibernate jdbc.batch_size设定大于0的情况,将hibernate.jdbc.batch_size修改为0即可消除。

<hibernate-configuration>
<session-factory>
...
<property name='hibernate. jdbc.batch_size">0</property>
...
</session-factory>
</hibernate-configuration>

再次尝试启动代码,发现依然无法成功运行,抛出异常如下:

Java代码 复制代码

  1. Hibernate: select hibernate_sequence.nextval from dual
  2. Hibernate: insert into T--USER (name, age, image,resume,id) values(?,?,?,?,?)
  3. 19:02:21,054 ERROR JDBCExceptionReporter:58 一IO异常:Connection reset bypeer: socket write error
  4. 19:02:21,054 ERROR JDBCExceptionReporter:58 一I。异常:Connection reset by peer:socket write error
  5. 19:02:21 。064 ERROR JDBCExceptionReporter:58一Io异常:Connection reset by peer: socket wr主to error
  6. 19:02:21,064 ERROR Sessionlrnpl:2399 一Could not synchronize database state with session
  7. net.sf.hibernate.exception.GenericJDSCException: could not insert:[com.redsaga.hibernate.db.entity.TUser#27]
  8. ...
 
Hibernate: select hibernate_sequence.nextval from dual 
Hibernate: insert into T--USER (name, age, image,resume,id) values(?,?,?,?,?) 
19:02:21,054 ERROR JDBCExceptionReporter:58 一IO异常:Connection reset bypeer: socket write error 
19:02:21,054 ERROR JDBCExceptionReporter:58 一I。异常:Connection reset by peer:socket write error 
19:02:21 。064 ERROR JDBCExceptionReporter:58一Io异常:Connection reset by peer: socket wr主to error 
19:02:21,064 ERROR Sessionlrnpl:2399 一Could not synchronize database state with session 
net.sf.hibernate.exception.GenericJDSCException: could not insert:[com.redsaga.hibernate.db.entity.TUser#27] 
... 

为什么会出现这样的情况?
问题出在Oracce中Blob/Clob字段独特的访问方式,Oracle Blob/Clob字段本身拥有一个游标(cursor) , JDBC必须通过游标对Blob/ Clob字段进行操作,在Blob/Clob字段被创建之前,我们无法获取其游标句柄,这也就意味着,我们必须首先创建一个空Blob/Clob字段,再从这个空Blob/Clob字段获取游标,写入我们所期望保存的数据。
如果用JDBC代码来表示这个过程,则得到如下代码:

Java代码 复制代码

  1. //... 获取JDBC连接
  2. dbconn.setAutoCommit(falee);
  3. // =======插入数据,BLOB CLOB字段插入空值
  4. PreparedStatenent preStmt=
  5. dbconn.prepareStatement(
  6. "insert into T_USER (name, age, id,image,resume) values
  7. (?,?,?,?,?)");
  8. preStmt.setString(1,"Shark");
  9. preStmt.setInt(2,20);
  10. preStmt.setInt(3,5);
  11. // 通过oracle.sgl.BLOB/CLOB.empty_lob()方法构造空Blob/Clob对象
  12. preStmt.setBlob(4 ,oracle.sgl.BLOB.empty_lob());
  13. preStmt.setClob(5,oracle.sgl.CLOB.empty_lob());
  14. preStmt.executeUpdate();
  15. preStmt.close():
  16. //========== 再次从库表读出,获得Blob/Clob句柄
  17. preStmt=
  18. dbconn.prepareStatement(
  19. "select image,resume from T_USER where id=?for update');
  20. preStmt.setint(l,5);
  21. ResultSet rset=preStmt.executeQuery();
  22. // 注意我们这里需要引用Oracle原生BLOB定义,如果使用了Weblogic JDBC Vendor
  23. // 则应使用weblogic.jdbc.vendor.oracle. OracleThinBLob/OracleThinCLOb
  24. rset.next();
  25. oracle.sql.BLOB imqBlob = (oracle.sql.BLOB) rset.getBlob(1);
  26. oracle.sql.CLOB resClob = (oracle.sql.CLOB) rset.getClob(2);
  27. //======= 将二进创数据写入Blob
  28. FileInputStream inStream = new FileinputStream("c\\inimage.jpg");
  29. OutputStream outStream = imgBlob.getBinaryOutputStream();
  30. byte[] buf=new byte[10240];//10K 读取缓存
  31. int len;
  32. while((len=inStream.read(buf))>0){
  33. outStream.write(buf,0,len);
  34. }
  35. inStream.close();
  36. outStream.close():
  37. //======= 将字符串写入Clob
  38. resClob.putString(1 ,"This is my Glob"
  39. //======= 将Blob/Clob字段更新到数据序
  40. preStmt= dbconn.prepareStatement("update T_USER set image=?, resume=? where id=?");
  41. preStmt.setBlob(1,imgBlob);
  42. preStmt.setClob(2,resClob):
  43. preStmt.setlnt(3 ,5);
  44. preStmt.executeUpdate();
  45. preStmt.close():
  46. dbconn.commit();
  47. dbconn.close():
 
//... 获取JDBC连接 
dbconn.setAutoCommit(falee); 
// =======插入数据,BLOB CLOB字段插入空值 
PreparedStatenent preStmt= 
dbconn.prepareStatement( 
"insert into T_USER (name, age, id,image,resume) values 
(?,?,?,?,?)"); 
preStmt.setString(1,"Shark"); 
preStmt.setInt(2,20); 
preStmt.setInt(3,5); 
// 通过oracle.sgl.BLOB/CLOB.empty_lob()方法构造空Blob/Clob对象 
preStmt.setBlob(4 ,oracle.sgl.BLOB.empty_lob()); 
preStmt.setClob(5,oracle.sgl.CLOB.empty_lob()); 
preStmt.executeUpdate(); 
preStmt.close(): 
//========== 再次从库表读出,获得Blob/Clob句柄 
preStmt= 
dbconn.prepareStatement( 
"select image,resume from T_USER where id=?for update'); 
preStmt.setint(l,5); 
ResultSet rset=preStmt.executeQuery(); 
// 注意我们这里需要引用Oracle原生BLOB定义,如果使用了Weblogic JDBC Vendor 
// 则应使用weblogic.jdbc.vendor.oracle. OracleThinBLob/OracleThinCLOb 
rset.next(); 
oracle.sql.BLOB imqBlob = (oracle.sql.BLOB) rset.getBlob(1); 
oracle.sql.CLOB resClob = (oracle.sql.CLOB) rset.getClob(2); 
//======= 将二进创数据写入Blob 
FileInputStream inStream = new FileinputStream("c\\inimage.jpg"); 
OutputStream outStream = imgBlob.getBinaryOutputStream(); 
byte[] buf=new byte[10240];//10K 读取缓存 
int len; 
while((len=inStream.read(buf))>0){ 
outStream.write(buf,0,len); 
} 
inStream.close(); 
outStream.close(): 
//======= 将字符串写入Clob 
resClob.putString(1 ,"This is my Glob" 
//======= 将Blob/Clob字段更新到数据序 
preStmt= dbconn.prepareStatement("update T_USER set image=?, resume=? where id=?"); 
preStmt.setBlob(1,imgBlob); 
preStmt.setClob(2,resClob): 
preStmt.setlnt(3 ,5); 
preStmt.executeUpdate(); 
preStmt.close(): 
dbconn.commit(); 
dbconn.close(): 

上面的代码说明了Oracle中Blob/Clob字段操作的一般机制,那么,基于Hibernate的持久层实现中,应该如何对Blob/Clob字段进行处理?
我们知道,Hibernate底层数据访问机制仍然是基于JDBC实现,那么也就意味着我们必须在Hibernate中模拟JDBC的访问流程:

Java代码 复制代码

  1. TUser user=new TUser();
  2. user.setAge(new Integer(20));
  3. user.setName("Shark');
  4. user.setImage(Hibernate.createSlob(new byte [1])):
  5. user.setResume(Hibernate.createClob(" "));// 注意这里的参教是一个空格
  6. Transaction tx=session.beginTransaction();
  7. session.save(user):
  8. // 调用flush方法,强制Hibernate立即执行insert sql
  9. session.flush();
  10. // 通过refresh方法,强制Hibernate执行select for update
  11. session.refresh(user, LockMode.UPGRADE);
  12. // 向Blob写入实际内容
  13. oracle.sql.BLOB blob=(oracle.sql.BLOB)user.getImage();
  14. OutputStream out=blob. getBinaryOutputStream();
  15. FileInputStream imgis=new FileInputStream("C:\\inimage.jpg");
  16. byte[] buf=new byte[10240];//10K 缓存
  17. int len;
  18. while((len=imgis.read(buf))>0){
  19. out.write(buf,0,len);
  20. }
  21. imgis.close();
  22. out.close();
  23. // 向Clob写入实际内容
  24. oracle.sql.CLOB clob=(oracle.sgl.CLOB) user.getResume();
  25. java.io.Writer writer = clob.getCharacterOutputStream();
  26. writer.write("this is my resume');
  27. writer.close();
  28. session.save(user);
  29. tx.commit();
  30. <PRE class=java name="code">
  31. 实际应用中,对于Clob字段,我们可以简单地将其映射为String类型,不过在这种情况下需要注意,Oracle Thin Driver对Clob字段支持尚有欠缺,当Clob内容超出4000字节时将无法读取,而Oracle OCI Driver(需要在本地安装Oracle客户端组件)则可以成功地完成大容量Clob字段的操作。
  32. 上面的代码中,我们通过Session.save/flush/refresh方法的组合使用,实现了上面JDBC代码中的Blob/Clob访问逻辑。
  33. Blob/Clob 字段的Hibernate保存实现如上所述,相对来讲,读取则没有太多的障碍,之前的读取代码依然可以正常运行。
  34. 对于上面的实现,相信大家都感觉到了一些Bad Smell,如果Blob/Clob字段普遍存在,那么我们的持久层逻辑中可能遍布如此复杂的数据存储逻辑、并与数据库原生类紧密祸
  35. 如何解决这些问题?
  36. 回忆之前关于自定义数据类型的讨论。通过自定义数据类型我们可以对数据的通用特征进行抽象,那么,对于Oracle的Blob/Clob字段,我们是否可以也对其进行抽象,并以其作为所有Oracle Blob/Clob字段的映射类型?
  37. 下面的StringClobType实现了这一目标:
  38. <PRE class=java name="code">
  39. public class StringClobType implements UserType{
  40. private static final String ORACLE_DRIVER_NAME="Oracle JDBC driver";
  41. private static final int ORACLE_DRIVER_MAJOR_VERSION=9;
  42. private static final int ORACLE_DRIVER_MINOR_VERSION=0;
  43. public int[] sqlTypes(){
  44. return new int[] {Types.CLOB};
  45. }
  46. public Class returnedClass{
  47. return String.class;
  48. }
  49. public boolean equals(Object x, object y){
  50. return org.apache.commons.lang.ObjectUtils.equals(x, y);
  51. }
  52. public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
  53. throws HibernateException,SQLException{
  54. Clob clob=rs.getClob(names(O]);
  55. return(clob==null ? null:clob.getSubString(l, (int) clob.length())):
  56. }
  57. public void nullSafeSet(PreparedStatement st ,Object value, int index)
  58. throws HibernateException, SQLException{
  59. DatabaseMetaData dbMetaData=st.getConnection().getMetaData();
  60. if (value==null)
  61. st.setNull(index, sqiTypes()(0));
  62. else
  63. // 本实现仅仅适用于Oracle数据序9.0以上版本
  64. if
  65. (ORACLE_DRIVER_NAME.equals(dbMetaData.getDriverName( ,))(
  66. if((dbMetaData.getDriverMajorVersion()
  67. >=ORACLE-DRIVER-MAJOR-VERSION)
  68. &&(dbMetaData.getDriverMinorVersion()
  69. >=ORACLE-DRIVER-MINOR-VERSION)) {
  70. try {
  71. // 通过动态加载方式进免编译期对Oracle JDBC的依赖
  72. Class oracleClobClass=Class.forName('oracle.sgl.CLOB");
  73. // 动态调用createTemporary方法
  74. Class partypes[]=new Class[3];
  75. partypes[0]=Connection.class;
  76. partypes[1]=Boolean.TYPE;
  77. partypes(2]=Integer.TYPE;
  78. Method createTemporaryMethod=
  79. oracleClobClass.getDeclaredMethod(
  80. "createTemporaxy “,
  81. partypes);
  82. Field durationSessionField=
  83. oracleClobClass.getField("DURATION-SESSION");
  84. Object arglist[]=new 0bject[3]:
  85. Connection conn=
  86. st.getConnection().getMetaData().getConnection();
  87. // 数据库连接类型必须为OracleConnection
  88. // 莱些应用服务器会使用自带Oracle JDBC Wrapper,如Weblogic
  89. // 这里需要特别注意
  90. Class oracleConnectionClass=
  91. Class.forName("oracle.jdbc.OracleConnection");
  92. if(!oracleConnectionClass
  93. .isAssignableFrom(conn.getClass())){
  94. throw new HibernateException(
  95. "Must be a oracle.jdbc.OracleConnection:.
  96. +conn.getClass().getName());
  97. }
  98. arglist[0] = conn;
  99. arglist(1] = Boolean.TRUE;
  100. arolist[2] = durationSessionField.get(null);
  101. Object tempClob =createTemporaryMethod.invoke(null,arglist);
  102. partypes=new Class[l];
  103. partypes[0]=Integer.TYPE;
  104. Method openMethod =oracleClobClass.getDeclaredMethod("open",partypes);
  105. Field modeReadWriteField =oracleClobClass.getField("MODE_READWRITE");
  106. arglist = new Object(l];
  107. arglis[0] = modeReadWriteField.get(null);
  108. openMethod.invoke(tempClob, arglist);
  109. Method getCharacterOutputStreamMethod=oracleClobClass.getDeclaredMethod("getCharacterOutputStream',null) ;
  110. // call the getCharacterOutpitStream method
  111. Writer tempClobWriter =(Writer)getCharacterOutputStreamMethod.invoke(tempClob,null);
  112. // 将参数写入Clob
  113. tempClobwriter.write((String) value);
  114. tempClobWriter.flush();
  115. tempClobWriter.Close();
  116. // close clob
  117. Method closeMethod=oracleClobClass.getDeclaredMethod("close", null);
  118. closeMethod.invoke(tempClob, null);
  119. st.setClob(index, (Clob) tempClob);
  120. )catch (ClassNotFoundException e){
  121. throw new HibernateException("Unable to find a required class.\n"+e.getMessage()):
  122. }catch (NOSuchMethodException e){
  123. throw new HibernateException("Unable to find a required method.\n"+e.getMessage()):
  124. }catch (NoSuchFieldException e){
  125. throw new HibernateException("Unable to find a required field.\n"+e.getMessage());
  126. }catch (IllegalAccessException e){
  127. throw new HibernateException("Unable to access a required method or field.\n"+e.getMessage());
  128. catch (InvocationTargetException e){
  129. throw new HibernateException(e.getMessage());
  130. { catch (IOException e){
  131. throw new HibernateException(e.getMessage());
  132. }
  133. else {
  134. throw new HibernateException(
  135. "No CLOBS support.Use driver version"
  136. +ORACLE_DRIVER_MAJOR_VERSION
  137. +" ,minor"
  138. +ORACLE_DRIVER_MINOR_VERSION);
  139. }
  140. }else {
  141. String str = (String) value;
  142. StrinaReader r = new StringReader(str);
  143. St.setCharacterStream(index, r, str.length());
  144. }
  145. }
  146. public Object deepCopy(Object value){
  147. if(value==null)
  148. return null;
  149. return new String((String) value);
  150. }
  151. public boolean isMutable(){
  152. return false
  153. }
  154. }
  155. </PRE>
  156. <BR>
  157. <BR>上面这段代码,重点在于nullSafeSet方法的实现,nullSafeSet中通过Java Reflection机制,解除了编译期的Oralce JDBC原生类依赖。同时,借助Oracle JDBC提供的原生功能完成了Clob字段的写入,Clob字段的写入操作由于涉及特定数据库内部实现细节,这里就不多费唇舌,大家可参见Oracle JDBC Java Doc.
  158. <BR>这段代码是由笔者根据Ali Ibrahim, Scott Miller的代码修改而来的(原版请参见httpJ/www.hibemate, org /56.html ),支持Oracle 9以上版本,Oracle 8对应的实现请参见上述网址。
  159. <BR>同样的道理,读者可以根据以上例程,编写自己的ByteBlobType以实现byte[]到Blob的映射。
  160. <BR>另外,此代码必须运行在最新版的Oracle JDBC Driver上(笔者所用版本为Oracle9i9.2.0.5 for JDK1.4,如果使用9.2.0.3或之前版本则在新建l更却删除数据时可能会遇到“nomore data read from socket”错误)。
  161. <BR>
  162. <BR>  </PRE

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。