How to stream data to database BLOB using Hibernate (no in-memory storing in byte[])

前端 未结 3 488
死守一世寂寞
死守一世寂寞 2020-12-14 12:51

I\'m looking for a way to stream binary data to/from database. If possible, i\'d like it to be done with Hibernate (in database agnostic way). All solutions I\'ve found invo

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 13:22

    You are storing the Blob in your POJO SimpleBean. This means if the blob is larger than your heap space, anytime you work with this object or access the data field, you're going to get the OutOfMemoryError because the entire thing is loaded into memory.

    I don't think there's a way to set or get a database field using a Stream in hibernate, and HQL inserts only into SELECT statements.

    What you may have to do is remove the data field from the SimpleBean object so that it's not stored in memory when you load or save. But when you need to save a blob, you can use hibernate's save() to create the row, then use a jdbc PreparedStatement and the setBinaryStream() method. When you need to access the stream, you can use hibernate's load() method to get a SimpleBean object and do a jdbc select to get a ResultSet then use the getBinaryStream() method to read the blob. The docs for setBinaryStream() say:

    The data will be read from the stream as needed until end-of-file is reached.

    So the data won't be stored entirely in memory.

提交回复
热议问题