通过Spring JDBC流式传输数据,未知长度

Gan*_*alf 4 java spring jdbc

我目前有一个应用程序通过使用Spring JDBC [SqlLobValue]将byte []插入到我们的数据库中.问题是,这不是一种可扩展的数据接收方式,因为服务器在写入数据库之前缓冲内存中的所有数据.我想从HttpServletRequest Inputstream流式传输数据,但是我可以找到任何以Inputstream作为参数的类的构造函数也需要内容长度作为参数.在将数据发布到我的应用程序时,我不会,也不会要求用户知道内容长度.有没有解决这个限制的方法?

我找不到关于如果我为内容长度传递-1会发生什么的文档,但我的猜测是它会抛出异常.我不确定为什么他们不能让流继续读取,直到read(...)返回-1,这是InputStream的必需行为.

Ada*_*ter 8

我认为你的意思是"InputStream"而不是"OutputStream".我试过这个,但是我的JDBC驱动程序遇到了更大的问题,所以我不确定这是否真的有效.

InputStream inputStream = httpServletRequest.getInputStream();

int contentLength = -1; // fake, will be ignored anyway
SqlLobValue sqlLobValue = new SqlLobValue(
    inputStream,
    contentLength,
    new DefaultLobHandler() {
        public LobCreator getLobCreator() {
            return new DefaultLobHandler.DefaultLobCreator() {
                public void setBlobAsBinaryStream(PreparedStatement ps, int paramIndex, InputStream binaryStream, int contentLength) throws SQLException {
                    // The contentLength parameter should be the -1 we provided earlier.
                    // You now have direct access to the PreparedStatement.
                    // Simply avoid calling setBinaryStream(int, InputStream, int)
                    // in favor of setBinaryStream(int, InputStream).
                    ps.setBinaryStream(paramIndex, binaryStream);
                }
            };
        }
    }
);

jdbcTemplate.update(
    "INSERT INTO foo (bar) VALUES (?)",
    new Object[]{ sqlLobValue }
);
Run Code Online (Sandbox Code Playgroud)