Can a DAO call DAO?

拈花ヽ惹草 提交于 2019-11-29 01:31:39

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:

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

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