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)
如果您能使用Spring,我会建议以下改进:
独立于使用Spring,我将推荐以下内容:
一个改进的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)
我的建议:
例
// 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)