Is it fine to have several DAOs?

倖福魔咒の 提交于 2019-12-12 19:18:23

问题


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 DAOs for most of the entities.

Often times you'll work with generified DAOs, 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!