Over a million developers have joined DZone.

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.

· Java Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

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.

The Java Zone is brought to you by Stormpath—offering a complete, pre-built User Management API for building web and mobile applications, and APIs. Download our new whitepaper: "Build Versus Buy: Customer Identity Management for Web and Mobile Applications".

Topics:
java,sql,jdbc

Published at DZone with permission of Richard Freedman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}