I faced some issues in a project with spring and hibernate where the stream given to Blob is not closed.
Blob blob = Hibernate.getLobCreator(currentSession).createBlob(inputStream, size);
I can't use things like try with resources since the stream is only read after the transaction commits. One of my friends suggested a hacky way to do this. Basically, his idea was to close the stream once the reading is complete.
import java.io.IOException;
import java.io.InputStream;
public class InputStreamWrapper extends InputStream {
private InputStream inputStream;
public InputStreamWrapper(InputStream inputStream) {
this.inputStream = inputStream;
}
@Override
public int read() throws IOException {
int val = this.inputStream.read();
if (val != -1) {
return val;
} else {
this.inputStream.close();
return -1;
}
}
}
I've done a simple test and it works. I understand that there can be a performance issue with the if check. However, I think there are other caveats in this as well. Can someone shed some light on those?
Blob blob = Hibernate.getLobCreator(currentSession).createBlob(new InputStreamWrapper(inputStream), size);