Let's say I have two classes: one for Band and one for CD. I want to be able to access easily all CD from one Band and to find the Band of a CD.
My solution is to have a field Band
in CD, and a ArrayList<CD>
in Band.
But I don't find this is a good solution. Does anyone know of a better design for this scenario?
I see why you dislike the solution.
You are only storing the information once, but you have to update changes in both classes.
If you change the Band
of a CD
, you have to remove the CD
from the old Band
, set the Band
in the CD
, then add it to the new Band
.
That is of course complicated and prone to error.
Your classes don't have simple getters/setters. Instead, you have to implement a lot of logic in your domain classes to keep consistency.
The advantage is, of course, that you always have a the Band
of a CD
accessible and vice versa. Its a trade-off. A neccesary one, should you, for example, use a CD
's Band
as part of its equals
implementation.
Here is an interesting alternative, that may be advantegous in some situations:
Use your classes Band
and CD
only as simple POJOs and use another class (i.e. MusicService
) to resolve the relation:
class MusicService {
Band getBand(CD cd);
List<CD> getCDs(Band band);
addCD(Band band, CD cd);
}
Your solution totally makes sense. Actually that's the principle JPA
works with.
See Java Persistence/OneToMany. JPA is a pretty good reference on how implement your own ORM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With