Hi, my first post here. Thought i just add an example of an annotated entity with a parent/child association in same table since i've never found it myself when i needed it.
Also i would like feedback if my method is the standard/best/optimal way for doing this. Any suggestions is appreciated!
The entity (
not an organization but the concept is the same, each musicgenre can have sub genres and a parent genre),
Code:
import java.util.*;
import javax.persistence.*;
@Entity
@Table (name="music_genre")
public class MusicGenre {
@Id
@GeneratedValue (strategy=GenerationType.AUTO, generator="musicgenre_seq_gen")
@SequenceGenerator(name="musicgenre_seq_gen", sequenceName="MUSICGENRE_SEQ")
private Long id = new Long(-1);
@OneToOne
@JoinColumn (name="parent_id")
private MusicGenre parentMusicGenre = null;
@OneToMany (cascade=CascadeType.ALL)
@JoinColumn(name="parent_id")
private List<MusicGenre> childMusicGenres = new ArrayList<MusicGenre>();
private String name = "";
public MusicGenre() {
}
public MusicGenre(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public MusicGenre getParentMusicGenre() {
return parentMusicGenre;
}
public void setName(String name) {
this.name = name;
}
public void setParentMusicGenre(MusicGenre parentMusicGenre) {
this.parentMusicGenre = parentMusicGenre;
}
public void addChildMusicGenre(MusicGenre childMusicGenre) {
childMusicGenre.setParentMusicGenre(this);
childMusicGenres.add(childMusicGenre);
}
public List<MusicGenre> getChildMusicGenres() {
return Collections.unmodifiableList(childMusicGenres);
}
public void setChildMusicGenres(List<MusicGenre> childMusicGenres) {
this.childMusicGenres = childMusicGenres;
}
}