1

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:

  1. Perform a lookup for the User
  2. Call User.addProduct()
  3. 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 the ProductService 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.

user3690467
  • 3,049
  • 6
  • 27
  • 54
  • 1
    Assuming `ProductService` already exists, the second option sounds the most reasonable. I'd strongly advise against the first one, for the exact reason you yourself mentioned. Of course, it is paramount that the method in `ProductService` be transactional as well – crizzis Aug 22 '17 at 20:08
  • My services aren't transactional but my DAOs are, should i just perform the user lookup in the product DAO with the user DAO? Or is that bad practice and i should look into making my services transactional? – user3690467 Aug 22 '17 at 20:12
  • 1
    You should make sure that looking up the `User` and saving the `Project` are wrapped inside a transaction, otherwise at the instant the `Project` is being saved, there is no guarantee the previously looked up `User` still exists. Now, service methods are usually meant to perform business logic involving multiple DAO calls, so it is pretty logical to make them transactional. Personally, I'd perform the lookup in the service method – crizzis Aug 22 '17 at 20:27

0 Answers0