Stream data through Spring JDBC, unknown length

I currently have an application that inserts byte [] into our database using Spring JDBC [SqlLobValue]. The problem is that this is not a scalable way to get data, because the server buffers all the data in memory before writing to the database. I would like to pass data from the HttpServletRequest input stream, but all the constructors I can find for any classes that accept the input stream as an argument also require the length of the content as an argument. I do not want and will not require the user to know the length of the content when sending data to my application. Is there any way to limit this restriction?

I cannot find the documentation of what will happen if I pass -1 for the length of the content, but I assume this will throw an exception. I'm not sure why they couldn't just read the stream until read (...) returns -1, the required behavior of an InputStream.

+4
source share
1 answer

I assume that you meant "InputStream" and not "OutputStream". I tried this, but I had big problems with the JDBC driver, so I'm not sure if this really works.

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 } ); 
+8
source

All Articles