17

I have component which needs to update the database for the customer and customer address (via JDBC). Is it appropriate to call the CustomerAddressDAO from the CustomerDAO? Or create a separate "CustomerDataManager" component which calls them separately?

Jack BeNimble
  • 35,733
  • 41
  • 130
  • 213

2 Answers2

30

You can do it, but that doesn't mean you should. In these cases, I like to use a Service (CustomerService in this case) that has a method call that uses both DAOs. You can define the transaction around the service method, so if one call fails, they both roll back.

The problem with DAOs that call other DAOs is you will quite quickly end up with circular references. Dependency injection becomes much more difficult.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
5

Obviously, you can do it in different ways. But, to properly answer this question, you should start from your model. In the model, see if Address is an Entity (something with its own id and used also independently), or it is a value type (something that only makes sense in the context of a Customer. Then, you will have two cases:

  1. Address is a Entity: In this case, Address has its own Dao and Customer has its own Dao. Neither Dao should access the other one. If there is some logic that needs to manipulate the two, then that has to be in your application logic, not in Data Access Layer.

  2. Address is a value type associated with Customer: In this case, address does not have a separate DAO of itself. It is being saved/restored as part of the containing Customer object.

Conclusion: If properly designed, DAOs don't access each other (under standard situations).

Nazar Merza
  • 3,365
  • 1
  • 19
  • 19
  • 2
    "If there is some logic that needs to manipulate the two, then that has to be in your application logic, not in Data Access Layer." -- what if it needs to be transactional? (e.g, I need to make sure both Customer and Address are deleted) – Matt Jan 31 '18 at 19:23
  • This is a very good question! I think, in that scenario, it makes sense to have Address as a Value type associated with Customer. This allows to manipulate address together with customer, e.g. deletion of the two. – Nazar Merza Feb 01 '18 at 16:43