Follow this Blog!

Oct 13, 2010

f Comment

Hibernate Self Join - Create Database Tables

MenuHow to Do Self Join Many-To-Many Mapping In Hibernate
Hibernate Self Join - Create Database Tables
Hibernate Self Join - Create Java Class
Hibernate Self Join - Create Hibernate Configuration
Hibernate Self Join - Test Java Code
Amazon So our entity is Keyword, and each Keyword can have a set of Keywords as its parents and a set of keywords as its children. This means this mapping is many-to-many and we need a join table to represent the relationships! DON'T WORRY; a join table is simply a table that keeps track of who are whose parents and who are whose children. Questions?

The following is the SQL script to create the tables.
# table 'keyword' that's supposed to have a set of children and parents joined by keyword_to_keyword
create table keyword(
  keyword_id         int          not null auto_increment,
  title              varchar(255) not null,
  body               text         not null,
  last_modified_time timestamp    not null default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  create_time        timestamp    not null,
    
  primary key (keyword_id)
) engine=InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;

# self join table for keyword
create table keyword_to_keyword(
  keyword_to_keyword_id    int       not null auto_increment,
  parent_id             int      not null,
  child_id              int      not null,
  last_modified_time    timestamp not null default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  create_time           timestamp not null,
    
  primary key(keyword_to_keyword_id),
  unique key mffl_keyword_to_keyword_ids (parent_id,child_id),
  foreign key (parent_id) references keyword(keyword_id),
  foreign key (child_id) references keyword(keyword_id)
) engine=InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
As you can see 'keyword_to_keyword' is the table for keyword to join itself. The parent_id in keyword_to_keyword specifies the parent and child_id specifies the child. I included last_modified_time and create_time columns because it's my habit to know when a row was created and when it's last updated, but you don't have to if you don't want to. Questions? Let me know!

Now that we have our table in database let's create the corresponding Java class!

◀ Self Join Mapping in Hibernate Tutorial HomeCreate Java Class ▶
Please leave a comment here!
One Minute Information - by Michael Wen
Find Michael on Google or Facebook
ADVERTISING WITH US - Direct your advertising requests to Michael