Wednesday, December 3, 2008

Hibernate: Mapping an entity to itself - Parent / Child relashipship

Well I am kinda into Hibernate right now. Converting the project that I'm working on to Hibernate. We have a catalogue that has a Parent/Child relationship, similar to directory structure or some tree. Basically a catalogue/direcotry has another catalogue/directory as a child or parent. So basically this entity maps to itself (self-mapping so to speak).

Hibernate XML mapping file:

Mapping java class:

public class Catalogue {
  private int id;
  private String content;
  private Catalogue parent;
  private Set<Catalogue> children =
                new HashSet<Catalogue>();

  public Parent(){
  }

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getContent() {
    return content;
  }

  public void setContent(String content) {
    this.content = content;
  }

  public Set<Catalogue> getChildren() {
    return children;
  }

  public void setChildren(Set<Catalogue> children){
    this.children = children;
  }

  public void addChild(Catalogue child){
    child.setParent(this);
    children.add(child);
  }
 
  public String getParent() {
    return parent;
  }

  public void setParent(Catalogue parent) {
    this.parent = parent;
  }
}

No comments: