Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove boilerplate from db code

Tags:

java

jdbc

It seems that every time I want to perform a db query, I have to write the following:

Connection conn = null;
Statement stmt = null;
ResultSet rset = null;

try {
    conn = dataSource.getConnection();
    stmt = conn.prepareStatement(sql);
    // ...set stmt params
    rset = stmt.executeQuery();
    while(rset.next()) {
        // Do something interesting
    }
} finally {
    try { if (rset != null) rset.close(); } catch(SQLException e) { }
    try { if (stmt != null) stmt.close(); } catch(SQLException e) { }
    try { if (conn != null) conn.close(); } catch(SQLException e) { }
}

Is this really the best way to do this? Is there a way to at least reduce some of the clutter?

Edited: as some of the comments pointed out, this code wasn't long enough.

like image 612
itsadok Avatar asked Jul 02 '09 07:07

itsadok


People also ask

Does Spring remove the boilerplate code?

Spring Data JPA allows us to define derived methods that read, update or delete records from the database. This is very helpful as it reduces the boilerplate code from the data access layer.

Which helps in reducing a lot of boilerplate code?

The need for boilerplate can be reduced through high-level mechanisms such as metaprogramming (which has the computer automatically write the needed boilerplate code or insert it at compile time), convention over configuration (which provides good default values, reducing the need to specify program details in every ...

Is boilerplate code bad?

The problem with boilerplate is that it violates DRY. In essence, when you write boilerplate, you're repeating the same code (or very similar code) across a number of classes. When that code needs to get changed, it's not at all certain that the developer will remember all of the places that code was repeated.


2 Answers

Yes, use the Sping JDBC Template classes (http://static.springsource.org/spring/docs/2.0.x/reference/jdbc.html).

Or if you don't use Spring copy the template pattern that they are using in your own code.

like image 131
Nick Holt Avatar answered Sep 19 '22 03:09

Nick Holt


If you already have a DataSource you can use Spring JdbcTemplate for:

  • greatly reduced boilerplate code
  • have a good sql exception hierarchy to handle common database problems with specific runtime exceptions
  • (later with further Spring usage) use declarative transaction management

If it seems too heavy for the moment you could implement some utility classes and methods for the 'boilerplate part'. Studying the source of JdbcTemplate should help in this case.

like image 26
Csaba_H Avatar answered Sep 23 '22 03:09

Csaba_H