I find extending JdbcDaoSupport is the best way to do this:
- Already has setDataSource implemented
- Implements get/setJdbcTemplate which gives you a chance to either set your own (ie for setting an exception translator) in the config or just set the datasource and let the class create it for you.
- Implements initDao which is automatically called. Useful for creating any of the object based support classes (ie StoredProcedure).
Given your example it would look something like the following. This is not pseudo code. It isn't missing any properites. Its assumed the object will be created by using setDataSource or setJdbcTemplate. The JdbcTemplate will be created for me.
What I changed from your description:
- Instead of a RowCallbackHandler I used a RowMapper. The JdbcTemplate will take care of creating the list for me.
- Instead of an inner class I create one instance of an anonymous class. RowMapper is simple enough, an anonymous class works well.
- Left JdbcTemplate and datasource handling to the super class.
Code:
public class MyDao extends JdbcDaoSupport {
public MyDao() {
}
private RowMapper accountMapper = new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Account result = new Account();
result.setName(rs.getString(1));
result.setCompany(rs.getString(2));
result.setNumEmployees(rs.getInt(1));
return result;
}
};
public List getAccounts(String param) {
final String sql = "SELECT * from ACCOUNT where param = ?";
return getJdbcTemplate().query(sql, new Object[] { param }, accountMapper);
}
public void saveAccount(Account account) {
final String sql = "INSERT into ACCOUNT (name, company, numEmployees) values (?, ?, ?)";
int insertCount = getJdbcTemplate().update(sql,
new Object[] {account.getName(), account.getCompany(), new Integer(account.getNumEmployees())}
);
System.out.println(insertCount + " rows inserted");
}
}
And my sample Account class
Code:
public class Account {
private String name;
private String company;
private int numEmployees;
public int getNumEmployees() {
return numEmployees;
}
public String getCompany() {
return company;
}
public void setName(String name) {
this.name = name;
}
public void setNumEmployees(int numEmployees) {
this.numEmployees = numEmployees;
}
public void setCompany(String company) {
this.company = company;
}
public String getName() {
return name;
}
}