我正在研究Repository模式,我有点cnfuse。 我想知道这种模式是否可以与 DAO 模式共存。
我已经实现了一个简单的 Java 程序,它使用纯 JDBC 将数据保存在 PostgreSQL 中。
该程序有:
通用存储库
public interface Repository<T> {
void save(T type);
void update(T type);
void delete(T type);
Optional<T> findById(int id);
List<T> findAll();
}
扩展部门域模型通用存储库的接口:
public interface DepartmentRepository extends Repository<Department> {
Optional<T> findByName(String name);
}
扩展 Employee 域模型的通用存储库的接口:
public interface EmployeeRepository extends Repository<Employee> {
Optional<T> findByEmail(String email);
}
因此,我有实现这些存储库的具体类:
DepartmentRepositoryImpl
和EmployeeRepositoryImpl
。
具体类调用 DAO 中的方法来管理数据。
我的 DAO 是:
public interface DAO <T>{
int save(T type);
void update(T type);
void delete(T type);
Optional<T> findById(int id);
List<T> findAll();
}
public interface DepartmentDAO extends DAO<Department>{
Optional<T> findByName(String name);
}
public interface EmployeeDAO extends DAO<Employee>{
Optional<T> findByEmail(String email);
}
以及使用纯 JDBC 访问 Postgres 的具体类
DepartmentDAOImpl
和 EmployeeDAOImpl
。
我的问题是:这个结构有意义吗?我可以将存储库和 DAO 一起使用吗?
请,我很感激一些指导。
谢谢
存储库和 DAO 模式可能会结合在一起,正如您已经所做的那样,存储库实例将使用 DAO 实现来进行 CRUD DB 操作。
但是,一如既往,“视情况而定”;我建议您阅读网络上的一些文章,根据您的域和应用程序的复杂性对这种用法做出自己的看法。
第一个起点可以是这个 https://www.baeldung.com/java-dao-vs-repository 和这个 DAO 和 Repository 模式之间有什么区别?