微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

解决方法:

我认为你的意思是“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 }
);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐