所以我正在写一个个人项目来学习web编程,我偶然发现了DAO模式。我构建了一些类(模型),就像几乎所有的程序一样,它们是嵌套的(例如:类Payment引用了Author实例)。仅供参考,我没有使用任何映射器(将在以后的迭代中添加它们,并且我使用JDBC,而不是JPA)。
我的问题是:
当我创建PaymentJdbcDao时,我有一个方法,它将返回一些付款,但为了从数据库存储的对象创建此付款,我还必须到达作者(存储在一个单独的表中)。
我应该从PaymentJdbcDao调用UserJdbcDao来获取付款的作者吗?我是应该用连接修改查询以从两个实体中检索字段吗? PaymentJdbcDao应该调用UserService (我认为这不好,因为服务位于daos之上的层上),还是应该将作者引用作为对象删除,而只保留对author_id的引用?
哪种方法更适合实现这一点?或者有没有其他更好的做法?
谢谢。
发布于 2019-03-10 06:45:30
我称我的DAO (DataAccessObjects)为“存储库”。
Spring Data JPA也在做这件事。
所以我会创建一个UserRepository和一个PaymentRepository。
存储库可以由其他存储库或服务调用。
服务永远不应该被存储库调用。
UI ->服务->存储库。
您的PaymentRepository可能会返回如下所示的实体
public class PaymentEntity{
private long id;
private DateTime dateTime;
private UserEntity user;
}您的UserRepository可能会返回如下所示的实体
public class UserEntity{
private long id;
private DateTime lastLogin;
private List<PaymentEntity> payments;
}您的存储库可能如下所示。
public interface PaymentRepository{
PaymentEntity getPaymentById(long id);
List<PaymentEntity> getAllPayments();
}
public interface UserRepository{
UserEntity getUserById(long id);
List<UserEntity> getAllUsers();
}因此,您的PaymentRepository将调用UserRepository来获取用户的付款。
您的UserRepository将调用PaymentRepository来获取所有用户的付款
我希望我能帮到你
https://stackoverflow.com/questions/55081478
复制相似问题