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?
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.
You can call one DAO from another but also consider building CustomerAddressDAO in CustomerDAO (after all, it's about customer and I do not think you want to have customer address without the customer).
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:
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.
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).
来源:https://stackoverflow.com/questions/8988252/can-a-dao-call-dao