Suppose I have the following domain objects:
thus Cat has a many-to-one relationship with Owner and a many-to-many relationship with Vet (the inverse relation Owner.cats is not needed and not modeled)Code:class Owner { int id String name } class Vet { int id String name } class Cat { int id String name Owner owner List vets }
My business should retrieve a complete cat (with owner and vets) given a cat id.
Which dao methods should I create ?
For the many-to-one relationship I see 3 options:
option 1
* Cat getCat(int id)
-> only retrieve primitive properties, no relations
* void addOwner (Cat cat)
-> select o.* from owner o, cat c where c.owner = o.id and c.id = ?
* business method should call getCat and addOwner
option 2
* Cat getCat (int id)
-> retrieve primitive properties and the owner-id
-> cat.getOwner().setId (resultset.getInt("owner"))
* Owner getOwner(int id)
-> select * from owner where id = ?
* business method should call getCat and getOwner
option 3
* like option 2 but getCat(int catId) calls getOwner(int ownerId) itself
-> pro: prevents incomplete owner objects
-> con: dependencies between dao-methods (possibly between dao's)
I prefer option 2:
* pro: in cases you only need the owner's id, you get away with one query
* pro: you will probably need the method to retrieve an owner by id anyway
* con: incomplete Owner object if you forget to call getOwner
But for many-to-many relationships I think only option 1 is viable:
* void addVets (Cat cat)
-> finds all the vets and adds them to the cat
-> select v.* from vet v, cat_vet cv where cv.vet = v.id and cv.cat = ?
If I understood correctly, applying option 2 for many-to-many relations is known as the "n+1 problem" since you need a query per vet.
What are your opinions and/or experiences ?
Is it common to have dependencies between dao's ?
Are there any better options (besides using Hibernate) ?
Maarten


Reply With Quote