Hibernate One to Many Annotation Example


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

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


1. Technologies used

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


2. Create tables

We will use again the two tables : CUSTOMER and ORDERS:


We have a one-to-many relationship between CUSTOMER and ORDERS.


Tables script :


3. Project structure

Hibernate One to Many Annotation


4. Project dependencies


5. Model classes

We will define mapping inside the model classes through annotations.

To map the one to many relationship between CUSTOMER and ORDERS tables, we will annotate the orders property in Customer class by @OneToMany and we will annotate the customer property in Orders class by @ManyToOne.

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


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


6. Hibernate configuration file

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


7. Hibernate Utility


8. Test It

We create a customer that have two orders.


Output :

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


Download source code

  • Yusuf Çakmak

    Thanks for tutorial, very helpful. You have a typo your Order class.
    ERROR: Unknown column ‘AMMOUNT’ in ‘field list’

    • Walid RAHALI

      You’re welcome! yes you’re right..It’s amout instead of ammount. It’s okay now :)
      Thanks man.