Skip to content

Instantly share code, notes, and snippets.

@up1
Last active August 29, 2015 14:05
Show Gist options
  • Save up1/65ee70fdf2eeee522ab7 to your computer and use it in GitHub Desktop.
Save up1/65ee70fdf2eeee522ab7 to your computer and use it in GitHub Desktop.
Demo :: Refactoring DAO
public List<T> executeQuery(String sql, Object[] params, RowMapper<T> rowMapper) throws SQLException{
List<T> results = new ArrayList<T>();
ResultSet resultSet = getResultSet(sql, params);
while(resultSet.next()) {
results.add(rowMapper.mapRow(resultSet));
}
return results;
}
public List<Person> getAll() {
List<Person> allPerson = new ArrayList<Person>();
try {
Connection connection = this.dataSource.getConnection();
PreparedStatement prep = connection.prepareStatement("select * from person");
ResultSet resultSet = prep.executeQuery();
while (resultSet.next()) {
Person person = new Person();
person.setID(resultSet.getInt("ID"));
person.setFirstName(resultSet.getString("FIRSTNAME"));
allPerson.add(person);
}
} catch (Exception e) {
throw new RuntimeException("Cat not get all person");
}
return allPerson;
}
public List<Person> getAll() {
try {
String sql = "select * from person";
JdbcTemplate<Person> jdbcTemplate = new JdbcTemplate<Person>(this.dataSource);
return jdbcTemplate.executeQuery(sql, null, new PersonRowMapper());
} catch (Exception e) {
throw new RuntimeException("Cat not get all person");
}
}
public Person getPerson(int id) {
Person person = null;
try {
Connection connection = this.dataSource.getConnection();
PreparedStatement prep = connection.prepareStatement("select * from person where id=?");
prep.setInt(1, id);
ResultSet resultSet = prep.executeQuery();
if (resultSet.next()) {
person = new Person();
person.setID(resultSet.getInt("ID"));
person.setFirstName(resultSet.getString("FIRSTNAME"));
}
} catch (Exception e) {
e.printStackTrace();
}
return person;
}
public Person getPerson(int id) {
Person person = null;
try {
Connection connection = this.dataSource.getConnection();
PreparedStatement prep = connection.prepareStatement("select * from person where id=?");
prep.setInt(1, id);
ResultSet resultSet = prep.executeQuery();
if (resultSet.next()) {
person = mappingPerson(resultSet);
}
} catch (Exception e) {
e.printStackTrace();
}
return person;
}
private Person mappingPerson(ResultSet resultSet) throws Exception{
Person person = new Person();
person.setID(resultSet.getInt("ID"));
person.setFirstName(resultSet.getString("FIRSTNAME"));
return person;
}
public class PersonRowMapper extends RowMapper<Person> {
@Override
public Person mapRow(ResultSet resultSet) throws SQLException {
Person person = new Person();
person.setID(resultSet.getInt("ID"));
person.setFirstName(resultSet.getString("FIRSTNAME"));
return person;
}
}
public abstract class RowMapper<T> {
public abstract T mapRow(ResultSet resultSet) throws SQLException;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment