views:

403

answers:

3

Can this ever make sense?

Say I need to fetch an object from the DB which has a relation to another object (represented by a foreign key in the DB, and by a composition in my domain object). If in my first DAO I fetch the data for object 1, then call the dao for object 2, and finally (from within the first DAO, call the setter in object 1 and give it the previously fetched object 2).

I know I could do a join instead, but it just seems more logical to me to decouple the functionality (which is why I am skeptical about calling one dao from another). Or should I move some of the logic to the service layer?

Thanks

Update: I think I solved the problem with help from the answers: all I needed to do was add the following to my mapping of Object 1:

<one-to-one name="Object2" fetch="join"
        class="com...Object2"></one-to-one>

I didn't have to change anything else. Thanks for the help!

+6  A: 

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!

Tim
Thanks..this is what I am working towards. Could I please get an example of how this mapping would look (I'm not having much luck on google). Also, with the mappings correct, would I still need to specify a "join" in my DAO?
es11
@es11: I see you've solved your problem.. Glad I could help. To answer your question: What you've got seems sufficient, so no, outside of your mappings you wont have to declare any join when retrieving your objects from the DAO.
Tim
100% agreed Tim!
PieterG
+3  A: 

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.

Henryk Konsek
A: 

http://www.theserverside.com/discussions/thread.tss?thread_id=32661

This will help u..