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.
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.
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 ...
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.
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.
If you already have a DataSource you can use Spring JdbcTemplate for:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With