问题
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?
回答1:
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.
回答2:
Creating one DAO for the entire database doesn't scale well. The more database tables you add the larger it gets. In industry you'll almost always see a one to one DAO to table relationship. As always there are exceptions and caveats.
回答3:
As the name suggest, DAO that stands for Data Access Object, is an entity to access ONE object or class. It is standard software engineering and enterprise industry (esp. in Java) best practices to have one DAO for each business entity.
If you are reusing similar behavior and data among several DAOs it is often handy to create a base DAO and extends it by other DAOs.
Also read https://en.wikipedia.org/wiki/Data_access_object
回答4:
You should create one DAO for single Hibernate Model (in most cases). Model can be a representation of all table columns, part of table columns, or a composition of multiple table columns. It all depends on your needs.
When you want to do this (have single DAO mapping entity to multiple tables), when you want to separate hibernate model from business model.
来源:https://stackoverflow.com/questions/50532679/is-it-fine-to-have-several-daos