Reputation: 126
So I'm writing a personal project to learn about web programing and I came across the DAO pattern. I'd built some classes (models) and like almost any program, they are nested (ex: the class Payment has a reference to an Author instance). Just for the reference, I'm not using any mappers (will add them on a later iteration, and I'm using JDBC, not JPA).
My question is this:
When I create the PaymentJdbcDao I had a method what will return some Payment, but in order to create this payment from the database stored object I must reach also the Author (stored in a separated table).
Should I call UserJdbcDao from the PaymentJdbcDao in order to get the payment's author, should I alter the query with a join to retrieve the fields from both entities, should the PaymentJdbcDao call the UserService (I think this isn't good since the services are on the layer abobe the daos), or should I remove the author reference as an object and just hold a reference to the author_id?
Which of the abobe is the more appropriate way to accomplish this? Or is any other way which is a better practice?
Thanks.
Upvotes: 0
Views: 241
Reputation: 1292
I call my DAOs (DataAccessObjects) "Repositories".
Spring Data JPA is doing this as well.
So I would create a UserRepository and a PaymentRepository.
Repositories can be called by other Repositories or Services.
Services should never be called by Repositories.
UI -> Service -> Repository.
Your PaymentRepository could return an Entity like this
public class PaymentEntity{
private long id;
private DateTime dateTime;
private UserEntity user;
}
Your UserRepository could return an Entity like this
public class UserEntity{
private long id;
private DateTime lastLogin;
private List<PaymentEntity> payments;
}
Your Repositories could look like this.
public interface PaymentRepository{
PaymentEntity getPaymentById(long id);
List<PaymentEntity> getAllPayments();
}
public interface UserRepository{
UserEntity getUserById(long id);
List<UserEntity> getAllUsers();
}
So your PaymentRepository would call the UserRepository to get the User for your Payment.
And your UserRepository would call the PaymentRepository to get all users Payments
I hope I was able to help you
Upvotes: 1