People are Still Writing Straight JDBC Code?
I’ve been using frameworks for so long now, that I tend to forget that there are still apparently lots of Java developers out there still entirely hand-writing JDBC code.
I’ve been using Hibernate, JPA, and the Spring Framework for so long now, that I tend to forget that there are still apparently lots of Java developers out there still entirely hand-writing JDBC code – getConnection(), etc., and trying (sometimes) to manage the JDBC resources properly in the face of exceptions.
Two things bring this to mind.
First, I recently did a consulting gig for a client who had hand-written JDBC transactions, and they were experiencing locking issues caused by transactions that were leaked when an exception was thrown.
Second was this blog post where the author suggests a few ways to write “pretty database code” that automagically cleans up resources that would otherwise be leaked.
Unfortunately, the author is trying to patch a problem that he shouldn’t have created in the first place. Instead of annotating resources to be cleaned up, I would recommend the use of a library such Spring (see JDBCTemplate) that abstracts the resource management, so that you don’t have to deal with it at all.
In the case of the client mentioned earlier (who was using Spring and JPA), user-transactions should not have been used, when JPA, or even Spring’s JDBCTemplate could have been used to manage the transactions.
The moral of the story is, if you are doing something in your code repeatedly that is complex or requires tricky resource management, others have probably had the same problem, and someone has probably solved the problem elegantly. Look for the elegant solution. Google is your friend. Don’t cut-and-paste, and for heaven’s sake, don’t create a macro in your IDE to do the cut-and-paste for you.