Hibernate One to One Annotation Example

 

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

We will use the Hibernate One to One XML Mapping Example  and enhance it to support Hibernate annotations.

 

1. Technologies used

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

 

2. Database tables

We will reuse the same tables used in the previous tutorial : CUSTOMER and CUSTOMER_DETAIL

We have one-to-one relationship between CUSTOMER and CUSTOMER_DETAIL tables.

Hibernate-One-to-One-XML-Mapping

Tables script :

 

3. Project structure

We create a Maven based Java application.

Hibernate-One-to-One-Annotation-1

 

4. Project dependencies

 

5. Model classes

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

We will use @OneToOne annotation to create one-to-one relationship between the Customer and CustomerDetail entities.

Both entities share the same primary key value : customerId

customerId is also the foreign key in the CustomerDetail entity

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

Setting the fetch attribute to FetchType.LAZY, which is the default value, means that when we load an instance of the Customer entity (using query), Hibernate will not load implicitly the CustomerDetail instance linked to the Customer‘s instance loaded (if we call customer.getCustomerDetail(), we will get a NULL)

Setting the cascade attribute to CascadeType.ALL value means that all operations (save, update, ..) on Customer entity are propagated to CustomerDetail.

 

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

We have used @GenericGenerator to configure a custom generator that will be applied on customerId property.

The @PrimaryKeyJoinColumn indicates that the primary key of Customer entity is used as the foreign key in CustomerDetail entity.

 

6. Hibernate configuration file

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

 

7. Hibernate Utility

Build the SessionFactory and get session instance.

 

8. Test It

We will insert a new record in customer table.

Due to the using of the cascade attribute, the save operation on customer table will be also propagated to customerDetail table.

 

Output :

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

 

Download source code