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

旧巷老猫 提交于 2019-12-01 03:20:04

#概述

使用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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!