java-尝试将BLOB读取为InputStream,但出现Connection Closed错误. Spring3 getJdbcTemplate()
作者:互联网
我正在移动一个应用程序以使用Spring3框架,并且我有从Oracle数据库读取BLOB列的代码:
这有效:
String fileSqlStr =
"select file_id, file_content from cpm_file where file_id = 4";
PreparedStatement ps = conn.prepareStatement(fileSqlStr);
ResultSet rs = ps.executeQuery();
rs.next();
int fileId = rs.getInt("file_id");
InputStream fis = rs.getBinaryStream("file_content");
ExlBOMImporter ei = new ExlBOMImporter(fis);
但是,当我尝试使用JdbcTemplate bean在Spring中编写它时:
InputStream is = getJdbcTemplate().query(getFileContentSql, new RowMapper<InputStream>() {
public InputStream mapRow(ResultSet rs, int rowNum) throws SQLException {
OracleLobHandler lobHandler = new OracleLobHandler();
return lobHandler.getBlobAsBinaryStream(rs, "file_content");
}
}, fileId).get(0);
ExlImporter importer = new ExlBOMImporter(is);
importer.process();
我收到一个java.io.IOException:关闭连接异常.
我在想Spring必须在我处理输入流之前关闭InputStream的连接.你们有更好的书写方式吗?
编辑:对异常的一些更深入的了解:
java.io.IOException: Closed Connection
at oracle.jdbc.driver.OracleBlobInputStream.needBytes(OracleBlobInputStream.java:204)
at oracle.jdbc.driver.OracleBufferedStream.readInternal(OracleBufferedStream.java:169)
at oracle.jdbc.driver.OracleBufferedStream.read(OracleBufferedStream.java:143)
at org.apache.poi.util.IOUtils.readFully(IOUtils.java:92)
at org.apache.poi.util.IOUtils.readFully(IOUtils.java:77)
at oracle.jdbc.driver.OracleBlobInputStream.needBytes(OracleBlobInputStream.java:204)
解决方法:
是的,Spring在离开查询方法时将整理连接.
最简单的解决方案是在RowMapper中执行处理,例如
getJdbcTemplate().query(getFileContentSql, new RowMapper<Void>() {
public void mapRow(ResultSet rs, int rowNum) throws SQLException {
OracleLobHandler lobHandler = new OracleLobHandler();
InputStream inputStream = lobHandler.getBlobAsBinaryStream(rs, "file_content");
ExlImporter importer = new ExlBOMImporter(inputStream);
importer.process();
}
}, fileId);
如果只想处理第一行,则使用ResultSetExtractor代替RowMapper.
标签:jdbc,spring-3,spring,java 来源: https://codeday.me/bug/20191101/1984360.html