我正在尝试用 java 开发通用 DAO。我尝试了以下内容。这是 实现通用 DAO 的好方法?我不想使用 hibernate 。我试图让它尽可能通用,这样我就不必一遍又一遍地重复相同的代码。
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;
}
}
}
现在我有:
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;
}
}
最佳答案
我的建议:
- 不要编写通用的 DAO;当您意识到泛型类在特定情况下不能完全满足您的需求并且通常最终会变得越来越复杂以涵盖不断增加的用例时,它们就会回来咬您。最好编写特定于应用程序的 DAO,然后尝试在以后生成任何常见行为。
- 考虑使用 Spring JDBC编写特定于应用程序的 DAO,但比 JDBC 更紧凑且更不容易出错。此外,与 Hibernate 不同的是,Spring JDBC 仅充当原始 JDBC 的薄包装,为您提供更细粒度的控制和更多可见性。
示例
// Create or inject underlying DataSource.
DataSource ds = ...
// Initialise Spring template, which we'll use for querying.
SimpleJdbcTemplate tmpl = new SimpleJdbcTemplate(ds);
// Create collection of "Role"s: The business object we're interested in.
Set<Role> roles = new HashSet<Role>();
// Query database for roles, use row mapper to extract and create
// business objects and add to collection. If an error occurs Spring
// will translate the checked SQLException into an unchecked Spring
// DataAccessException and also close any open resources (ResultSet, Connection).
roles.addAll(tmpl.query("select * from Role", new ParameterizedRowMapper<Role>() {
public Role mapRow(ResultSet resultSet, int i) throws SQLException {
return new Role(resultSet.getString("RoleName"));
}
}));
关于java - Java 中的通用 DAO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2848692/