首页 > 解决方案 > 如何使用 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?这是一个错误还是我做错了什么?

标签: javaoraclemybatis

解决方案


您需要在会话打开时读取输入流。

假设您的映射器方法声明如下...

@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
    }
  }
}

推荐阅读