Read / write BLOB data in chunks using Hibernate

Is there a way to read and write from blob in chunks using Hibernate . Right now I am getting an OutOfmemoryException because all blob data is loaded into memory in byte[] .

To be more specific, let's say I want to save a large file in a database table called File .

 public class File { private byte[] data; } 

I open the file in FileInputStream, and then what? How do I tell Hibernate that I need streaming content and not pass the entire byte[] array at once? Should I use blob instead of byte[] ? Anyway, how can I transfer the content?

As for reading, is there a way by which I can say that hibernation (other than lazy loading), I need the blob to load into pieces, so when I return my File , it should not give me an OutOfmemoryException .

I use:

  • Oracle 11.2.0.3.0
  • Hibernate 4.2.3 final
  • Oracle Driver 11.2
+7
java oracle stream hibernate blob
source share
1 answer

If you're on a Blob route, have you tried using the Hibernate LobHelper createBlob method , which accepts an InputStream ? To create a Blob and save it to the database, you must specify the FileInputStream object and the number of bytes.

In your bean / entity class file, Blob might display like this (using JPA annotations):

 @Lob @Column(name = "DATA") private Blob data; // Getter and setter 

And a business logic / data access class could create a blob for your bean / entity so that it doesn't close the input stream before it remains in the database:

 FileInputStream fis = new FileInputStream(file); Blob data = getSession().getLobHelper().createBlob(fis, file.length()); fileEntity.setData(data); // Persist file entity object to database 

To go the other way and read Blob from the database as a stream in pieces, you can call the getBinaryStream method, giving you an InputStream and letting you set the buffer size if necessary:

 InputStream is = fileEntity.getData().getBinaryStream(); 

Struts 2 has a convenient configuration that can set the size of the InputStream result buffer .

+12
source share

All Articles