概述
使用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();
执行步骤:
-
- 获取 lobHandler 可以是 DefaultLobHandler
-
- 使用方法 setClobAsCharacterStream 设置CLOB内容
-
- 使用方法 setBlobAsBinaryStream 设置BLOB内容
其他方法
setBlobAsBinaryStream
setClobAsAsciiStream
setClobAsCharacterStream