Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DAO. Many-to-many relationship

How to handle many to many relationships when using DAO pattern? Is DAO responsible for linking two entities using 3-rd Link table? For example I have 2 entities: Customer and Product.

And I need to provide methods like:

public void assignCustomerToProduct(...);
public List<Product> getSelledProducts(long customerId);

This methods requires using 3-rd table as Linkage table. Is CustomerDao responsible for providing this method? Or it's better to exclude this methods into service-layer?

like image 512
WelcomeTo Avatar asked Nov 03 '22 05:11

WelcomeTo


1 Answers

One of the objects should own the relationship. So for example positions are only saved when you save an Employee.

If you do this, then Employee becomes a (a bit) like an Aggregate Root (if you're talking about DDD repositories). The repository is then responsible from creating the position if required and inserting the many-to-many entry in the link table.

If Position is an aggregate root itself, then the EmployeeRepository is only responsible for updating the link table, but is not responsible for persisting Positions.

like image 180
Augusto Avatar answered Nov 08 '22 12:11

Augusto