Problems with the traditional JDBC

The following are the problems we have to face whenever we work with the traditional JDBC API:

  • Redundant results due to error-prone code: The traditional JDBC API required a lot of tedious code to work with the data access layer. Let's see the following code to connect the Database and execute the desired query:
        public List<Account> findByAccountNumber(Long accountNumber) { 
          List<Account> accountList = new ArrayList<Account>(); 
          Connection conn = null; 
          String sql = "select account_name,
account_balance from ACCOUNT where account_number=?"; try { DataSource dataSource = DataSourceUtils.getDataSource(); conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ps.setLong(1, accountNumber); ResultSet rs = ps.executeQuery(); while (rs.next()) { accountList.add(new Account(rs.getString(
"account_name"), ...)); } } catch (SQLException e) { /* what to be handle here? */ } finally { try { conn.close(); } catch (SQLException e) { /* what to be handle here ?*/ } } return accountList; }

As you can see in the preceding code, there are some lines which are highlighted; only this bold code matters-the rest is boilerplate. Also, this code handles the SQLException in the application inefficiently, because the developer doesn't know what should be handled there. Let's now look at another problem in the traditional JDBC code.

  • Leads to poor exception handling: In the preceding code, the exceptions in the application are handled very poorly. The developers are not aware of what exceptions are to be handled here. SQLException is a checked Exception, which means it forces the developers to handle errors, but if you can't handle it, you must declare it. It is a very bad way of handling exceptions, and the intermediate methods must declare exception(s) from all methods in the code. It is a form of tight coupling.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset