I am trying to develop generic DAO in java. I have tried the following. Is this a good way to implement generic DAO? I don't want to use hibernate. I am trying to make it as generic as possible so that I don't have to repeat the same code over and over again.
public abstract class AbstractDAO<T> {
protected ResultSet findbyId(String tablename, Integer id){
ResultSet rs= null;
try {
// the following lines are not working
pStmt = cn.prepareStatement("SELECT * FROM "+ tablename+ "WHERE id = ?");
pStmt.setInt(1, id);
rs = pStmt.executeQuery();
} catch (SQLException ex) {
System.out.println("ERROR in findbyid " +ex.getMessage() +ex.getCause());
ex.printStackTrace();
}finally{
return rs;
}
}
}
Now I have:
public class UserDAO extends AbstractDAO<User>{
public List<User> findbyid(int id){
Resultset rs =findbyid("USERS",id) // "USERS" is table name in DB
List<Users> users = convertToList(rs);
return users;
}
private List<User> convertToList(ResultSet rs) {
List<User> userList= new ArrayList();
User user= new User();;
try {
while (rs.next()) {
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setFname(rs.getString("fname"));
user.setLname(rs.getString("lname"));
user.setUsertype(rs.getInt("usertype"));
user.setPasswd(rs.getString("passwd"));
userList.add(user);
}
} catch (SQLException ex) {
Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return userList;
}
}
close()
on JDBC objects such asResultSet
when you are done with them. Where are you going to callclose()
on yourResultSet
? – Fountainhead