spring + mybatis 存取clob

    存的时候会比较麻烦,需要使用select for update的方式更新数据,如果原来没有这一条数据,还需要先新增,新增的时候需要将clob字段存为oracle.sql.CLOB.empty_lob((),然后用create for update 方式查询出来这一条数据,查询出的clob字段需要用clob.putString方式定义,最后才能用update语句将clob字段更新到数据库中。mybatis不能完成上面那么复杂的操作,所以我的解决方式是直接拿spring管理的链接,然后用jdbc方式完成。需要注意的是,使用使用原始jdbc方式操作数据时,和mybatis的对数据库的操作要分开,如果放在同一个事务里面,很容易锁表。

    查询的时候需要注意,jdbcType="CLOB" javaType="java.lang.String"。

下面附上别人的代码

 Oracle中处理BLOB/CLOB字段的方式比较特别,所以需要特别注意下面两点:

1. 在Oracle JDBC中采用流机制对 BLOB/CLOB 进行读写操作,所以要注意不能在批处理中读写 BLOB/CLOB字段,否则将出现
Stream type cannot be used in batching 异常。

2. Oracle BLOB/CLOB 字段本身拥有一个游标(cursor),JDBC通过游标对Blob/Clob字段进行操作,在Blob/Clob字段创建之前,无法获取其游标句柄,会出现
Connection reset by peer: socket write error 异常。
           

PreparedStatement ps=conn.prepareStatement("insert into PICTURE(image,resume) values(?,?)");
//通过oralce.sql.BLOB/CLOB.empty_lob()构造空Blob/Clob对象 
ps.setBlob(1, oracle.sql.BLOB.empty_lob());
ps.setClob(2, oracle.sql.CLOB.empty_lob());

ps.excuteUpdate();
ps.close();




//再次对读出Blob/Clob句柄 
ps=conn.prepareStatement("select image,resume from PICTURE where id=? for update");
ps.setInt(1 , 100);

ResultSet rs=ps.executeQuery();
rs.next();
oracle.sql.BLOB imgBlob=(oracle.sql.BLOB)rs.getBlob(1);
oracle.sql.CLOB resClob=(oracle.sql.CLOB)rs.getClob(2);
 
//将二进制数据写入Blob 
FileInputStream inStream=new FileInputStream("c://image.jpg");
OutputStream outStream=imgBlob.getBinaryOutputStream();
byte[] buf=new byte[10240];
int len;
while(len=inStream.read(buf)>0){
outStream.write(buf, 0 ,len);
} 
inStream.close();
outStream.cloese();


//将字符串写入Clob 
resClob.putString(1, "this is a clob");

//再将Blob/Clob字段更新到数据库 
ps=conn.prepareStatement("update PICTURE set image=? and resume=? where id=?");
ps.setBlob(1, imgBlob);
ps.setClob(2, resClob);
ps.setInt(3, 100 );

ps.executeUpdate();
ps.close();
原文地址:https://www.cnblogs.com/sigm/p/7258098.html