Spring 数据库处理Clob/Blob大对象

来源:互联网 发布:清理软件残留 编辑:程序博客网 时间:2024/05/20 06:50

概述

使用Spring的时候需求上难免说需要存储一下几种类型:

  • 文本
  • 图片
  • 二进制

处理对象

Spring 支持通过LobCreator/LobHandler进行处理大对象

  • BLOB
    • byte[] — getBlobAsBytes and setBlobAsBytes
    • InputStream — getBlobAsBinaryStream and setBlobAsBinaryStream
  • CLOB
    • String — getClobAsString and setClobAsString
    • InputStream — getClobAsAsciiStream and setClobAsAsciiStream
    • Reader — getClobAsCharacterStream and setClobAsCharacterStream

入口

图片标题

看到方法名就知道,在调用前会被执行一遍,刚好看看这个对象的实现,只有AbstractLobCreatingPreparedStatementCallback,接下来看看源码,看看有没有例子。
图片标题
就是我想要的

使用例子

final File blobIn = new File("spring2004.jpg");final InputStream blobIs = new FileInputStream(blobIn);final File clobIn = new File("large.txt");final InputStream clobIs = new FileInputStream(clobIn);final InputStreamReader clobReader = new InputStreamReader(clobIs);jdbcTemplate.execute(    "INSERT INTO lob_table (id, a_clob, a_blob) VALUES (?, ?, ?)",    //new DefaultLobHandler() or new OracleLobHandler()    new AbstractLobCreatingPreparedStatementCallback(lobHandler) {         protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {            ps.setLong(1, 1L);            lobCreator.setClobAsCharacterStream(ps, 2, clobReader, (int)clobIn.length());             lobCreator.setBlobAsBinaryStream(ps, 3, blobIs, (int)blobIn.length());         }    });blobIs.close();clobReader.close();

执行步骤:

    1. 获取 lobHandler 可以是 DefaultLobHandler
    1. 使用方法 setClobAsCharacterStream 设置CLOB内容
    1. 使用方法 setBlobAsBinaryStream 设置BLOB内容

其他方法

setBlobAsBinaryStream setClobAsAsciiStream setClobAsCharacterStream

0 0