Wednesday, January 25, 2012

How to make many-to-one relationships on the same table with Hibernate

As a developer you may find your self in a situation where an entity may have many children entities of the same type.As an example consider the case where a Category may consists of many sub-Categories.It may be obvious that the previously mentioned example is a clear one-to-many/many-to-one relationship.Let 's see now how such a relationship can be implemented using Hibernate.

Beginning from the database side the category table will look something like this:

create table 'category '(
`id` int(11) NOT NULL AUTO_INCREMENT,
 `name_of_the_category` varchar(150) NOT NULL,
 `parent_category` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`),
KEY `name_of_the_category` (`name_of_the_category`),
 KEY `FK_1` (`parent_category`),
 CONSTRAINT `FK_1` FOREIGN KEY (`parent_category`) REFERENCES `category` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


In the above listing we created a database table named "Category",with fields: id ,name_of_the_category,parent_category and a foreign key between "parent_category" and "id" columns

The next step is to crate th POJO that will represent the database table:

public class Category {
 private int id;
 private String categoryName;
 private Set subCategories;
 private Category parentCategory;
  public int getId() {
 return id;
 }
  public void setId(int id) {
 this.id = id;
 }
  public String getCategoryName() {
 return categoryName;
 }
  public void setCategoryName(String categoryName) {
 this.categoryName = categoryName;
 }
   public Category getParentCategory() {
 return parentCategory;
 }
  public void setParentCategory(Category parentCategory) {
 this.parentCategory = parentCategory;
 }
 public String toString(){
 return getCategoryName();
 }
  public Set getSubCategories() {
 return subCategories;
 }
  public void setSubCategories(Set subCategories) {
 this.subCategories = subCategories;
 }
 }


Read more: Java-only
QR: LoadTutorial.javaonly?id=5

Posted via email from Jasper-Net