My question is somewhat similar to In which layer should I join 2 entities together? but I could not find a suitable answer.
Using JPA with Hibernate if relevant.
I have a model class User
which has a one-to-many relationship with the class Product
. A Product
can not exist without a user.
After the form submission part of my app, I receive an instance of Product
and a User
's ID; the product has not been linked to a User
instance. To perform the association I need to:
- Perform a lookup for the
User
- Call
User.addProduct()
- Persist changes to both models
My question is from a design perspective, where should these steps take place? From what I see I have 3 options:
- Perform the lookup in the controller method and use the separate services to persist (does not benefit from the transactional DAO methods)
- Pass the ID and the
Product
instance in a method call to theProductService
which would perform the user lookup using the user DAO and persist both. - Same as previous but in the
UserService
I'm probably missing some correct approaches but which approach follows best practice? What is the convention?
I'm using @Transactional on my DAOs so the first approach would not get and update both entities in the same transaction from what I understand.