firstthumb
firstthumb

Reputation: 4754

I want to insert a file to Oracle using BLOB column type over Hibernate?

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?

Upvotes: 0

Views: 6843

Answers (2)

Vanger
Vanger

Reputation: 326

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.

Upvotes: 1

Vanger
Vanger

Reputation: 326

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;

}

Upvotes: 1

Related Questions