我如何使用 MyBatis BlobInputStreamTypeHandler / ClobReaderTypeHandler 来流式传输 select 请求的内容?
How do I use MyBatis BlobInputStreamTypeHandler / ClobReaderTypeHandler to stream content of select request?
我需要获取 BLOB 内容并将其存储在某处(假设它是文件)。 BLOB 内容可能很大,所以我想使用流来执行此操作。在 MyBatis 'Configuration XML' page 上有一个可用的类型处理程序列表。我发现有 BlobInputStreamTypeHandler 应该允许我获得 InputStream 而这正是我所需要的。所以我在 xml 配置中为我的查询指定了 resultType="java.io.InputStream"
。但是,当我尝试从执行 'read from DB' 方法后获得的 InputStream 读取数据时,我得到 java.io.IOException: Closed Connection
。
我试图弄清楚并发现 class org.apache.ibatis.executor.resultset.DefaultResultSetHandler
is closing 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
}
}
}
我需要获取 BLOB 内容并将其存储在某处(假设它是文件)。 BLOB 内容可能很大,所以我想使用流来执行此操作。在 MyBatis 'Configuration XML' page 上有一个可用的类型处理程序列表。我发现有 BlobInputStreamTypeHandler 应该允许我获得 InputStream 而这正是我所需要的。所以我在 xml 配置中为我的查询指定了 resultType="java.io.InputStream"
。但是,当我尝试从执行 'read from DB' 方法后获得的 InputStream 读取数据时,我得到 java.io.IOException: Closed Connection
。
我试图弄清楚并发现 class org.apache.ibatis.executor.resultset.DefaultResultSetHandler
is closing 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
}
}
}