Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent a 1..n relationship in Java

Tags:

java

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?

like image 232
trnsnt Avatar asked Aug 29 '13 11:08

trnsnt


2 Answers

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);
}
  • Advantages: Separation of concerns, stateless services
  • Disadvantage: More code
like image 70
Jonas Eicher Avatar answered Oct 02 '22 06:10

Jonas Eicher


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.

like image 33
dic19 Avatar answered Oct 02 '22 08:10

dic19