Let's say I have one database with two tables: companies
and employees
.
Should I create companyDAO
and employeeDAO
If I select, update, add and remove from those two tables?
Or I should create one DAO in which I'll write methods for CRUD operations for every table in the database?
Yes, it makes sense to have separate DAO
s for most of the entities.
Often times you'll work with generified DAO
s, i.e. you have an abstract super class. In a simplified example, it could look like this:
class BaseDAO<T extends Entity>
that provide a bunch of useful methods to find, remove or update the entities. When defining a subclass of that BaseDAO for each Entity, e.g.
class EmployeeDAO extends BaseDAO<Employee>
you make sure that all your DAOs return the correct type for the methods which you only have to implement in your BaseDAO. So, the findAll()
method in your EmployeeDAO will return List<Employee>
.
Moreover you can implement methods for customized operations for certain entities, e.g. findEmployeesWithSalaryAbove(long)
in the respective class. You don't want these to clutter a single DAO.