Mock tests, Interview questions, Tutorials and Tech news
 
 
Home > Education, Programming / tutorials > One-to-One mapping in Hibernate using Foreign Key Association

One-to-One mapping in Hibernate using Foreign Key Association

February 16th, 2010 smitha Leave a comment Go to comments

One-to-One mapping can be done in 2 ways:

  1. Primary key association:
  2. Foreign key association.

My previous post described about the Primary key one-to-one mapping in Hibernate. This post gives an example of Foreign key one-to-one association in Hibernate.

In Foreign key one-to-one mapping,  2 entities will have one to one association using foreign keys. one  table holds primary key of 2nd table. Eg: consider Customer and address entities. In primary key association,  both the tables share same primary key. In foreign key association, customer table will have a address_id columns, in which primary key (address_id) of the customer’s address will be saved. Both customer and address tables will have different primary keys.

The tables would look like below:

create table address(
    address_id int(11) not null auto_increment,
    address_line1 varchar(100) not null,
    address_line2 varchar(100),
    city varchar(50) not null,
    state varchar(50) not null,
    pincode int(10) not null,
    primary key(address_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),
    address_id int(11),
    primary key(customer_id),
    foreign key(address_id) references address(address_id));

 

Address is a simple table and customer table contains a column to store the corresponding address_id.

Corresponding Beans would be with following fields and their getter and setter methods:

public class Address {

 long addressId;
 String addressLine1;
 String addressLine2;
 String city;
 String state;
 Integer pincode;
 Customer customer;

 

public class Customer {
 Long customerId;
    String name;
    String emailAddress;
    String contactNo;
    Address address;

 

The Hibernate mapping files would look like below:

Address.hbm.xml:

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 3.0//EN”
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd“>

<hibernate-mapping>
  <class name=”entities.Address” table=”ADDRESS”>
    <id name=”addressId” type=”long” column=”address_id” >
     <generator/>
  </id>
  
  <property name=”addressLine1″>
     <column name=”address_line1″ />
    </property>
   
    <property name=”addressLine2″>
     <column name=”address_line2″ />
    </property>
   
    <property name=”city”>
     <column name=”city” />
    </property>
   
    <property name=”state”>
     <column name=”state” />
    </property>
   
    <property name=”pincode”>
     <column name=”pincode” />
    </property>
  </class>
</hibernate-mapping>

 

address.hbm.xml is simple and there is no much complications.

Customer.hbm.xml:

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 3.0//EN”
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd“>

<hibernate-mapping>
  <class name=”entities.Customer” table=”CUSTOMER”>
    <id name=”customerId” type=”long” column=”customer_id” >
     <generator/>
  </id>
  
  <property name=”name”>
     <column name=”NAME” />
    </property>
   
    <property name=”emailAddress”>
     <column name=”email_id” />
    </property>
   
    <property name=”contactNo”>
     <column name=”contact_no” />
    </property>

    <many-to-one name=”address”
                column=”address_id”
                cascade=”all”  unique=”true”
                />
  </class>
</hibernate-mapping>

 

Point to note here is the Many-to-one tag. We are associating the entities with one-to-one but we are using a many-to-one tag. When using many-to-one in one-to-one mapping, we ignore the ‘many’ part. We are not caring how many address are bound to a customer, but here we ensure that only one customer (to-one part) is bound to an address.

In customer class, by defining the address variable as below:

 Address address;

 (As its not a List/Set or collection) we ensure that its just an one-to-one relationship.

 Now we can test it using following code:

// save customer
         Customer customer = new Customer();
         customer.setName(“Surya”);
         customer.setEmailAddress(“surya@gmail.com“);
         customer.setContactNo(“91-932686876″);
         Address address = new Address();
         address.setAddressLine1(“xxx-street, near Surya Complex”);
         address.setCity(“Pune”);
         address.setState(“Maharashtra”);
         address.setPincode(11111);
        
         customer.setAddress(address);
         address.setCustomer(customer);
         session.save(customer);

   //fetch all customers
           
            Query query = session.createQuery(“from Customer customer”);
            for(Iterator it=query.iterate();it.hasNext();){
             Customer customer1 = (Customer) it.next();
             Address address1 = customer1.getAddress();
                System.out.println(“customer ID: ” + customer1.getCustomerId());
                System.out.println(“Name: ” + customer1.getName());
                System.out.println(“address: ” + address1.getAddressLine1());
                System.out.println(address1.getAddressId());
                System.out.println(address1.getAddressLine2());
                System.out.println(address1.getCity());
                System.out.println(address1.getState());
                System.out.println(address1.getPincode());
              }

 

To download full code of above example please click here.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Mixx
  • Google Bookmarks
  • IndianPad
  • Reddit
  1. Ruchi
    January 5th, 2012 at 00:14 | #1

    Very nice code to understand foreign key mapping in hibernate

  2. jacob
    March 22nd, 2011 at 06:37 | #2

    it is very good example to practice

  3. bkrakesh
    January 20th, 2011 at 01:48 | #3

    Hi,

    You can use Annotation instead of using HBM files to map. There is no confusion of writing the mapping file.

    All you need to do is just use the annotation oneToOne , and it has some parameters like , casscade type and joinColumn.

    and two pojo classes for the two table mapping.

    please have look at the clean example in

    http://j2eereference.com/2011/01/one-to-one-mapping-using-hibernate/

    [This is not a site promotion ]

    Regards,
    Rakesh.

  4. Smitha
    October 7th, 2010 at 11:24 | #4

    using @OneToOne(mappedBy=”attribute_name_on_the_reverse_side”) you can do it.

  5. Ziad
    October 6th, 2010 at 02:28 | #5

    First of all, thank you for this good and easy tutorial.
    I’ve a quetion please: In this case, how we can add the biderctionality to this mapping?

    Thank you,

    Ziad.

  6. Smitha
    May 11th, 2010 at 13:48 | #6

    the <one-to-one tag can be used with entities which share same primary key. When associating entities, one entity having other table’s primary key as a field, can only be associated using <many-to-one tag. Here <one-to-one tag can’t be used.

  7. Stephane
    May 11th, 2010 at 08:43 | #7

    Can you delve more on the rationale not to use a one-to-one mapping over your preffered many-to-one ?
    What is the inconvenience in that case of using a one-to-one mapping ?

    Thanks !

  1. No trackbacks yet.
Get Adobe Flash playerPlugin by wpburn.com wordpress themes