java中的泛型DAO

aks*_*hay 7 java dao genericdao

我正在尝试在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;
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

我现在有:

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;

    }
}
Run Code Online (Sandbox Code Playgroud)

Esp*_*pen 6

如果您能使用Spring,我会建议以下改进:

  • 让Spring进行异常处理.
  • 使用JdbcTemplate而不是自己创建预准备语句.

独立于使用Spring,我将推荐以下内容:

  • 不要将表名作为参数发送.这应该在初始化阶段完成.
  • 在id参数上使用String,因为它更通用.
  • 考虑返回通用对象而不是集合,因为集合应始终只包含一个对象.

一个改进的AbstractDao与Spring:

import java.util.Collection;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public abstract class AbstractDao<T> {

    protected final RowMapper<T> rowMapper;

    protected final String findByIdSql;

    protected final JdbcTemplate jdbcTemplate;

    protected AbstractDao(RowMapper<T> rowMapper, String tableName,
            JdbcTemplate jdbcTemplate) {
        this.rowMapper = rowMapper;
        this.findByIdSql = "SELECT * FROM " + tableName + "WHERE id = ?";
        this.jdbcTemplate = jdbcTemplate;
    }

    public  Collection<T> findById(final String id) {
        Object[] params = {id};
        return jdbcTemplate.query(findByIdSql, params, rowMapper);
    }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,没有异常处理或使用原始SQL类进行黑客攻击.此模板为您关闭ResultSet,我在您的代码中看不到.

而UserDao:

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class UserDao extends AbstractDao<User> {

    private final static String TABLE_NAME = "USERS";

    public UserDao(JdbcTemplate jdbcTemplate) {
        super(new UserRowMapper(), TABLE_NAME, jdbcTemplate);
    }

    private static class UserRowMapper implements RowMapper<User> {
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setUserName(rs.getString("username"));
            user.setFirstName(rs.getString("fname"));
            user.setLastName(rs.getString("lname"));

            return user;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

当您知道id和id对应于数据库中的单个行时,您应该考虑返回一个通用对象而不是一个集合.

public T findUniqueObjectById(final String id) {
    Object[] params = {id};
    return jdbcTemplate.queryForObject(findByIdSql, params, rowMapper);
}
Run Code Online (Sandbox Code Playgroud)

这使您的服务代码更具可读性,因为您不需要从列表中检索用户,而只需:

User user = userDao.findUniqueObjectById("22");
Run Code Online (Sandbox Code Playgroud)


Ada*_*ski 5

我的建议:

  • 不要写一个通用的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"));
  }
}));
Run Code Online (Sandbox Code Playgroud)


Mat*_*ARD 0

不要重新发明轮子,你已经可以找到这样做的好项目,例如google 上的generic-dao项目。

编辑:可能回答得太快了,谷歌项目是基于 JPA 的,但尽管如此,您可以使用其中的一些概念。