Hibernate One to One XML Mapping Example

 

In this example, we will see how to perform one to one mapping in Hibernate using XML mapping files.

 

1. Technologies used

  • Hibernate 4.3.6.Final
  • MySQL 5.1
  • Maven 3.0.5
  • Eclipse 4.2
  • JDK 1.7

 

2. Create tables

We will consider that we have two tables : CUSTOMER and CUSTOMER_DETAIL

Assuming that a customer can have exactly one detail and a detail belongs to one customer only, so we will use a one-to-one association.

Hibernate-One-to-One-XML-Mapping

In CUSTOMER table, CUSTOMER_ID is primary key

In CUSTOMER_DETAIL table, CUSTOMER_ID is primary key and foreign key.

 

Tables script :

 

3. Project structure

We create a Maven based Java application.

Hibernate-One-to-One-XML-Mapping-1

 

4. Project dependencies

 

5. Model classes

We create two model classes to persist the objects related to CUSTOMER and CUSTOMER_DETAIL tables.

File : src/main/java/com/keylesson/persistence/Customer.java

File : src/main/java/com/keylesson/persistence/CustomerDetail.java

 

6. Mapping files

It both files, we will use one-to-one tag to implement the one-to-one association.

File : src/main/resources/com/keylesson/persistence/Customer.hbm.xml

 

File : src/main/resources/com/keylesson/persistence/CustomerDetail.hbm.xml

 

7. Hibernate configuration file

File : src/main/resources/hibernate.cfg.xml

 

8. Hibernate Utility

To get the session instance.

 

9. Test It

We add a customer record in the database :

 

Output :

Hibernate: insert into CUSTOMER (TITLE, NAME) values (?, ?)
Hibernate: insert into CUSTOMER_DETAIL (ADDRESS, TEL, CREATION_DATE, CUSTOMER_ID) values (?, ?, ?, ?)

 

Download source code

  • Rajesh

    Sir, Your Tutorial is very Nice and very Helpful to us…
    Thanks for your time for helping us with solved examples….