In dit voorbeeld heb ik een stuk code gebruikt uit de UserDAO uit het vorige project. Daarin had ik 3 keer dezelfde code geschreven:
public List<User> getTeachers() {
List<User> resultList = new ArrayList<>();
String sql = "SELECT * FROM `User` WHERE role = ?;";
try {
setupPreparedStatement(sql);
.setString(1, "Docent");
preparedStatementResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
= new User(resultSet.getInt("userId"),
User user .getString("userName"),
resultSet.getString("password"),
resultSet.getString("firstName"),
resultSet.getString("infix"),
resultSet.getString("surname"),
resultSet.getString("role"));
resultSet.add(user);
resultList}
} catch (SQLException sqlError) {
System.out.println(sqlError.getMessage());
}
return resultList;
}
@Override
public User getOneById(int id) {
User user = null;
String sql = "Select * From User Where userId = ?;";
try {
setupPreparedStatement(sql);
preparedStatement.setInt(1, id);
ResultSet resultSet = executeSelectStatement();
while (resultSet.next()) {
user = new User(resultSet.getInt("userId"),
resultSet.getString("userName"),
resultSet.getString("password"),
resultSet.getString("firstName"),
resultSet.getString("infix"),
resultSet.getString("surname"),
resultSet.getString("role"));
}
} catch (SQLException foutmelding) {
System.out.println(foutmelding.getMessage());
}
return user;
}
public User getOneByName(String name) {
User user = null;
String sql = "Select * From User Where userName = ?;";
try {
setupPreparedStatement(sql);
preparedStatement.setString(1, name);
ResultSet resultSet = executeSelectStatement();
while (resultSet.next()) {
user = new User(resultSet.getInt("userId"),
resultSet.getString("userName"),
resultSet.getString("password"),
resultSet.getString("firstName"),
resultSet.getString("infix"),
resultSet.getString("surname"),
resultSet.getString("role"));
}
} catch (SQLException foutmelding) {
System.out.println(foutmelding.getMessage());
}
return user;
}
Dat zou efficiƫnter kunnen door deze methodes te combineren in een methode:
private User createUserFromResultSet(ResultSet resultSet) throws SQLException {
return new User(
resultSet.getInt("userId"),
resultSet.getString("userName"),
resultSet.getString("password"),
resultSet.getString("firstName"),
resultSet.getString("infix"),
resultSet.getString("surname"),
resultSet.getString("role")
);
}