Calling one DAO from another DAO?

心已入冬 提交于 2019-11-30 10:20:14

In reading this I can only conclude that most likely, you're doing it wrong.. ;)

If you setup your mappings right between ObjectA and ObjectB (could be OneToOne, OneToMany or ManyToMany), Hibernate will (lazy)load the reference from A to B automatically. This will eliminate the need to query the second DAO, and set the ObjectB reference in ObjectA.

Take this one step further and you might not even need the DAO for ObjectB!

I personally prefer to avoid references between the DAOs. If I need a data fetched by DAO to perform another operation I decouple the DAOs:

// Bad - have to inject Dao into antoher Dao
class FooDao extends BaseDao {
  BarDao barDao;

  public Foo complexLoad() {
    return doFooStuff(barDao.loadBar());
  }
}

// Good - dependency on Bar only, not to Dao
class FooDao extends BaseDao {
  public Foo complexLoad(Bar bar) {
    return doFooStuff(bar);
  }
}

Then I inject both DAOs into the service.

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