Sunday, February 21, 2010

Mapping Composite Keys in Hibernate

In Real world applications it is natural to have tables with composite keys. The row will be identified with combination of key  column values of a row.

Consider Following scenario:

A test selling website defines tests and customers.

   create table test(
   test_id int(11) not null auto_increment,
   test_name varchar(100),
   test_desc varchar(150),
   test_questions varchar(5),
   primary key(test_id));

   create table customer(
       customer_id int(11) not null auto_increment,
       name varchar(50) not null,
       email_id varchar(100),
       contact_no varchar(20),
       primary key(customer_id));

To keep track of tests purchased by customers it maintains following table:

   create table tests_purchased(
   customer_id int(11) not null,
   test_id int(11) not null,
   created_date datetime not null,
   primary key(customer_id, test_id));

Primary key of this table is combination of customer and test id.
To map such classes we have to use <composite-key> tag.  Both the test_id and customer_id acts as identifier to the tests_purchased table.

Read more: Skill Guru

Posted via email from jasper22's posterous