How to present 1..n relationships in Java

Let's say I have two classes: one for the group and one for the CD. I want to be able to easily access all CDs from one group and find the CD group.

My solution is to have the Band field on the CD and ArrayList<CD> in the group.

But I do not think this is a good solution. Does anyone know of a better design for this scenario?

+4
source share
4 answers

I understand why you do not like the solution.

You save information only once, but you must update changes in both classes.

If you change the Band to a CD , you need to remove the CD from the old Band , install the Band in the CD , and then add it to the new Band >.

This, of course, is complicated and error prone.

There are no simple getters / setters in your classes. Instead, you should implement a lot of logic in your domain classes in order to maintain consistency.

The advantage, of course, is that you always have a Band available CD and vice versa. This is a compromise. For example, if you, for example, use the CD Band as part of the equals implementation.

Here is an interesting alternative that may be beneficial in some situations:

Use the Band and CD classes only as simple POJOs and use another class (i.e. MusicService ) to resolve the relationship:

 class MusicService { Band getBand(CD cd); List<CD> getCDs(Band band); addCD(Band band, CD cd); } 
  • Advantages: Separation of problems, stateless services
  • Downside: more code
+3
source

Your decision makes sense. Actually, the JPA principle works. See Java Persistence / OneToMany . JPA is a pretty good recommendation on how to implement your own ORM.

+1
source

You may have Set CDs in the Band class.

Alternatively, save a unique identifier in the Band class that will display each unique group with multiple CDs.

There is no need to have the Band box on the CD as I understand it.

0
source

You do not save information twice: the CD just holds the pointer to the Band class. If this were done in C ++, it would require some thinking (e.g. weak_ptr for Band on the CD to avoid circular references), but in Java GC will take care of deleting both objects when Band is no longer mentioned.

You can provide some consistency (for example, a CD in only one strip) by writing code that takes care of this, for example, the code below (WARNING: NOT TESTED):

 class Band { private List<CD> m_cds; public void addCD(CD cd) { id(cd.getBand() == this) { return; } if(cd.getBand() != null) { cd.getBand().removeCd(CD cd); } cd.setBand(this); m_cds.add(cd); } public void removeCd(CD cd) { cd.setBand(null); m_cds.remove(cd); } } class CD { private Band m_band; public void setBand(Band band) { m_band = band; } public Band getBand() { return m_band; } } 
0
source

Source: https://habr.com/ru/post/1499605/


All Articles