如何将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;
}
但我认为这是一种错误的做法。有人可以帮我这个吗?
答案 0 :(得分:0)
您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;
}
...
现在您可以在任何地方使用它。 e.g。
@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());
}