利用spring的jdbcTemplate处理blob、clob

spring定义了一个以统一的方式操作各种数据库的Lob类型数据的LobCreator(保存的时候用),同时提供了一个LobHandler为操作二进制字段和大文本字段提供统一接口访问。
举例,例子里面的t_post表中post_text字段是CLOB类型,而post_attach是BLOG类型:

String sql = " INSERT INTO t_post(post_id,user_id,post_text,post_attach)"
     + " VALUES(?,?,?,?)";
   getJdbcTemplate().execute(
     sql,
     new AbstractLobCreatingPreparedStatementCallback(
       this.lobHandler) {
      protected void setValues(PreparedStatement ps,
        LobCreator lobCreator) throws SQLException {
       ps.setInt(1, incre.nextIntValue());
       ps.setInt(2, post.getUserId());
       //存储文件流,text文本之类
        //存储图片用lobCreator.setBlobAsBinaryStream(ps, 3, inputstream,inputstream.avaliable)
       lobCreator.setClobAsAsciiStream(ps, 3, inputstream,inputstream.avaliable);
       lobCreator.setClobAsAsciiStream(ps, 4, inputstream,inputstream.avaliable);
      }
     });
}
}

读取BLOB/CLOB块,举例:

public List getAttachs(final int userId){
   String sql = "SELECT post_id,post_attach FROM t_post where user_id =? and post_attach is not null";
   return getJdbcTemplate().query(
       sql,new Object[] {userId},
       new RowMapper() {
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
        Post post = new Post();
        int postId = rs.getInt(1);
         byte[] attach = lobHandler.getBlobAsBytes(rs, 2);
         post.setPostId(postId);
         post.setPostAttach(attach);
         return post;
        }
       });
}

Spring 让 LOB 数据操作变得简单易行 另一篇介绍
http://www.ibm.com/developerworks/cn/java/j-lo-spring-lob/

你可能感兴趣的:(spring,sql,IBM,Blog,J#)