Spring 數據庫處理Clob/Blob大對象

#概述java

使用Spring的時候需求上不免說須要存儲一下幾種類型:spring

  • 文本
  • 圖片
  • 二進制

處理對象

Spring 支持經過LobCreator/LobHandler進行處理大對象code

  • 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 setClobAsCharacterStreamci

相關文章
相關標籤/搜索