java - 如何使用 MyBatis BlobInputStreamTypeHandler / ClobReaderTypeHandler 流式传输选择请求的内容?
问题描述
我需要获取 BLOB 内容并将其存储在某处(假设它是文件)。BLOB 内容可能很大,所以我想使用流来执行此操作。在MyBatis 的“配置 XML”页面上有一个可用类型处理程序的列表。我发现有 BlobInputStreamTypeHandler 应该允许我获取 InputStream,而这正是我所需要的。所以我resultType="java.io.InputStream"
在 xml 配置中为我的查询指定了。但是,java.io.IOException: Closed Connection
当我尝试从“从数据库读取”方法执行后得到的 InputStream 读取数据时,我得到了。我试图弄清楚,发现类org.apache.ibatis.executor.resultset.DefaultResultSetHandler
正在关闭 resultSet,这使得流不可读。
当我尝试使用 ClobReaderTypeHandler 从 CLOB 获取 Reader 时,我得到了同样的异常。
我正在使用 mybatis 3.5.4 版本。
如何从 CLOB 或 BLOB 列获取 Reader/InputStream?这是一个错误还是我做错了什么?
解决方案
您需要在会话打开时读取输入流。
假设您的映射器方法声明如下...
@Select("select bindata from users where id = #{id}")
InputStream selectBlob(Integer id);
获取和读取输入流的代码看起来像这样。
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
Mapper mapper = sqlSession.getMapper(Mapper.class);
try (InputStream inputStream = mapper.selectBlob(1)) {
byte[] buffer = new byte[1024];
int read;
while((read = inputStream.read(buffer)) > -1) {
// use the read data
}
}
}
推荐阅读
- wordpress - WP 或函数添加额外的 br 标签
- apache-nifi - 如何在 Nifi 中将属性设置为空白字符串
- javascript - Laravel - 收藏/取消收藏按钮
- android - 如何存储远程配置的默认数组?
- php - '$wpdb->get_results' 帖子显示在单独的 ccs 表中 - 需要一个表
- c# - PHP 与 C#/.NET 之间的 TripleDES 加密
- python - 如何从字典中接收裸字符串,末尾没有双引号或括号或括号?
- python - 删除嵌套列表中字符串值中的撇号
- ruby-on-rails - Ruby on Rails - 从某些路由中排除单个域
- r - 链接到弹出窗口中的图像(R 传单)