如何使DAO对象成为其他DAO的属性?
假设我有一个带有Department属性的Employee对象
public class Employee {
public Department;
//setter and getters
}我有这个EmployeeDAO和DepartmentDAO接口以及相应的实现
我有DAOFactory
public abstract class DAOFactory {
// db connection instantiation here
public IEmployeeDAO getEmployeeDAO() {
return new EmployeeDAOImpl(this);
}
public IDepartmentDAO getDepartmentDAO() {
return new DepartmentDAOImpl(this);
}}
我有一个servlet来实例化这个DAOfactory
public class EmployeeController extends HttpServlet {
public EmployeeController() {
super();
DBUtils dbInstance = DBUtils.getInstance("mysql");
System.out.println("DAOFactory successfully obtained: " + dbInstance);
// Obtain UserDAO.
employeeDAO = dbInstance.getEmployeeDAO();
departmentDAO = dbInstance.getDepartmentDAO();
jobDAO = dbInstance.getJobDAO();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
employees = employeeDAO.findAll();
request.setAttribute("employees", employees);
}我的问题是,当我调用employeeDAO的findAll方法时,如何映射employeeDAO内部的Department或它的实现?
在我试图绘制结果的过程中,我遇到了这样的情况:
private Employee map(ResultSet rs) throws SQLException {
Employee employee = new Employee();
employee.setEmployeeID(rs.getInt("EMPLOYEE_ID"));
employee.setFirstName(rs.getString("FIRST_NAME"));
employee.setLastName(rs.getString("LAST_NAME"));
Department department = new DepartmentDAOImpl().getDepartmentByID(rs
.getInt("DEPARTMENT_ID"));
employee.setDepartment(department);
return employee;
}但我认为这是一个错误的方法。有人能帮我吗?
发布于 2016-06-05 14:09:00
您的EmployeeDAOImpl依赖于IDepartmentDAO。与其直接实例化EmployeeDAOImpl,不如将其声明为依赖项,并让构造该的代码知道如何解决该问题。
假设
interface IEmployeeDAO {
Employee load(long id);
}
interface IDepartmentDAO {
Department load(long id);
}由于接口需要构造函数中所需的dao
class EmployeeDAOImpl implements IEmployeeDAO {
private final DAOFactory factory;
private final IDepartmentDAO departmentDAO;
public EmployeeDAOImpl(DAOFactory factory, IDepartmentDAO departmentDAO) {
this.factory = factory;
this.departmentDAO = departmentDAO;
}
...现在你可以在任何地方使用它了。例如:
@Override
public Employee load(long id) {
...
long departmentId = ....
Department department = departmentDAO.load(departmentId);
employee.department = department;
return employee;
}知道使用哪种实现的DAOFactory现在可以通过添加一个简单的参数来提供依赖关系。
public IEmployeeDAO getEmployeeDAO() {
return new EmployeeDAOImpl(this, getDepartmentDAO());
}https://stackoverflow.com/questions/37642413
复制相似问题