Tuesday, March 24, 2009

Oracle JDBC driver rant (writing BLOB)

I haven't touched JDBC and J2EE in general for quite some years. How was I surprised when I saw that J2EE is still quirky... After all these years...

Anyways, simple problem: when using proper J2EE way to get a database connection from J2EE datasource, most datasource implementations (JBoss in my case) will return connection/resultset wrappers. Now, oracle JDBC driver fails to write to BLOB when being wrapped. And, the fact that I need to import and use oracle-specific classes to write to BLOB in the first place, is, well, just ridiculous...

Thanks god, spring comes to help here (with support for various app servers, including tomcat):

http://static.springframework.org/spring/docs/1.1.5/api/org/springframework/jdbc/support/nativejdbc/JBossNativeJdbcExtractor.html

Now, here's a code to write blobs without importing oracle.jdbc.* and oracle.sql.* classes and without manually unwraping connections:

NativeJdbcExtractor jdbcExtractor = new JBossNativeJdbcExtractor();
OracleLobHandler handler = new OracleLobHandler();
handler.setNativeJdbcExtractor(jdbcExtractor);
.......
PreparedStatement ps = connection.prepareStatement("update xxx set segment=? where id='" + id + "'");
handler.getLobCreator().setBlobAsBytes(ps, 1, bytes);
ps.execute();


Looks neat, right? The downside is that you will need 3 spring jars (almost a megabyte) to have this nice feature. And of course, you can inject a proper jdbc extractor from config file if you need to, this is spring, after all.

So, this is how you can use spring even if you don't use it :)