Can a DAO call DAO?

帅比萌擦擦* 提交于 2019-11-27 16:02:23

问题


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?


回答1:


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.




回答2:


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).




回答3:


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).



来源:https://stackoverflow.com/questions/8988252/can-a-dao-call-dao

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!