When I search the web for inserting BLOBs into Oracle database with jdbc thin driver, most of the webpages suggest a 3-step approach:
empty_blob()
The Oracle server's LOB handling is pretty poor and can suffer from serious performance problems (e.g. massive overuse of the redo log), so the first solution may be a way to address those.
I would suggest trying both approaches. if you have a competent DBA, they may be able to advise which approach has the lowest impact on the server.
I found a simple call to setObject(pos, byte[])
works for my case.
From Database Programming with JDBC and Java By George Reese,
byte[] data = null;
stmt = con.prepareStatement("INSERT INTO BlobTest(fileName, "
+ "blobData) VALUES(?, ?)");
stmt.setString(1, "some-file.txt");
stmt.setObject(2, data, Types.BLOB);
stmt.executeUpdate();
Another point of view from Oracle DBA. Sun guys did very poor job when they designed JDBC standards(1.0, 2.0, 3.0, 4.0). BLOB stands for large object and therefore it can be very large. It is something that can not be stored in JVM heap. Oracle thinks of BLOBs as something like file handles(it fact they are call then "lob locators"). LOBS can not be created via constructor and are not Java objects. Also LOB locators(oracle.sql.BLOB) can not be created via constructor - they MUST be created in the DB side. In Oracle there are two ways how to create a LOB.
DBMS_LOB.CREATETEMPORATY - the returned locator in this case points into temporary tablespace. All the writes/reads against this locator will be sent via network onto DB server. Nothing is stored in JVM heap.
Call to EMPTY_BLOB function. INSERT INTO T1(NAME, FILE) VALUES("a.avi", EMPTY_BLOB()) RETURNING FILE INTO ?; In this case returned lob locator points into data tablespace. All the writes/reads against this locator will be sent via network onto DB server. All the writes are "guarded" by writes into redo-logs. Nothing is stored in JVM heap. The returning clause was not supported by JDBC standards (1.0, 2.0), therefore you can find many examples on the internet where people recommend approach of two steps: "INSERT...; SELECT ... FOR UPDATE;"
Oracle lobs must be associated with some database connection, they can not be used when DB connection is lost/closed/(or "commited"). They can not be passed from one connection to another.
You second example can work, but will require excessive copying if data from temporary tablespace into data tablespace.