views:

827

answers:

2

I want to save my file on Oracle Instance. I am using Hibernate for data objects. How can I insert files into Oracle Blob. Is there any sample code for this?

+1  A: 

In first you must annotate your entity field with @javax.persistance.Lob annotation. Like this:

public class InfoMessage {

    private byte[] body;

    @Lob
    public byte[] getBody() {
     return body;
    }

    public void setBody(byte[] body) {
     this.body = body;
    }
}

and set it with bytes array. It's depends on wich File class you use. The first google result for java.io.File. I guess there's better solution for this operation.

public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();

if (length > Integer.MAX_VALUE) {
    // File is too large
}

// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];

// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
       && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
    offset += numRead;
}

// Ensure all the bytes have been read in
if (offset < bytes.length) {
    throw new IOException("Could not completely read file "+file.getName());
}

// Close the input stream and return bytes
is.close();
return bytes;

}

Vanger
Thanks for your answer Vanger. I am using xml configuration for hibernate not annotation.
Firstthumb
@Vanger Can I store 3GB file on Oracle? Because with this code you are using Integer and length of byte array can be Max of Integer and this is less than 3GB file. Am I wrong?
Firstthumb
+1  A: 

The @Lob annotation is not Hibernate's one. It's javax.persistence and you can use it in entity bean with any hibernate mapping. Yes, the big file is obvious problem for such example. But i can't find any workaround for this case. FileInputStream using int type value to represent offset point. I googled this one with similiar problem: http://www.coderanch.com/t/449055/Streams/java/JAVA-HEAP-SIZE-files-byte You can use solution with SQLPrepareSteatement if you use Java 1.6. Othwerwise you can try to use BufferedReader and somehow convert results to byteArray[] and try to beat another problem: you'll need so much memory as file size is.

EDITED: Another thing: Oracle can append data to it's clob\blob fields using dbms_lob.writeappend() procedure so you can avoid having all file in memory, but will GC perform clean as fast as BufferedReader read from file. And seems it's not a hibernate work to do this... jdbc and PreparedStatements back again.

Vanger
+1 for clear explanation. Thanks. I got my answer.
Firstthumb