Example of One to Many Mapping using annotation in Hibernate

In this article, we will cover how is @OnetoMany mapping is made using Annotation in Hibernate. If you want to learn how to do @onetomany mapping without annotation you can check this article How to Map Collection in Hibernate?.

What is @OneToMany Mapping?

The mapping between two entities in which one entity is related to a second entity with the One to Many relationships and the second entity is related to a first entity with the many to one relationship.

Example: As we know, while building any E-commerce application we have a Category Entity and a Product Entity where One category has multiple products, and in turn, Many Products are related to one Category.

Following is the  database representation of @onetoMany Relationship

One to Many Mapping using annotation in Hibernate

Create an Entity class- Category.java 

Create a class and use the annotation @Entity and @Table to map the class to the Relation. Here, We have used @OnetoMany annotation to create a relation of One to Many and also created the Set of Products.

package com.onetomany.entity;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "Category")
public class Category {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private int categorId;

  @Column(name = "cname", length = 100)
  private String categoryName;

  @Column(name = "cdesc", length = 100)
  private String categoryDesc;

  @OneToMany(mappedBy = "category")
  private Set<Product> products = new HashSet<>();

  public int getCategorId() {
    return categorId;
  }

  public void setCategorId(int categorId) {
    this.categorId = categorId;
  }

  public String getCategoryName() {
    return categoryName;
  }

  public void setCategoryName(String categoryName) {
    this.categoryName = categoryName;
  }

  public String getCategoryDesc() {
    return categoryDesc;
  }

  public void setCategoryDesc(String categoryDesc) {
    this.categoryDesc = categoryDesc;
  }

  public Set<Product> getProducts() {
    return products;
  }

  public void setProducts(Set<Product> products) {
    this.products = products;
  }

  public Category(int categorId, String categoryName, String categoryDesc, Set<Product> products) {
    super();
    this.categorId = categorId;
    this.categoryName = categoryName;
    this.categoryDesc = categoryDesc;
    this.products = products;
  }

  public Category() {
    // TODO Auto-generated constructor stub
  }

  @Override
  public String toString() {
    return "Category [categorId=" + categorId + ", categoryName=" + categoryName + ", categoryDesc=" + categoryDesc
        + ", products=" + products + "]";
  }

}

Create Product.java Entity class and Map the Category entity with @ManyToOne mapping.

package com.onetomany.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "products")
public class Product {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private int productId;
  @Column(name = "pname" , length = 100)
  private String productName;
  @Column (name = "price", length = 100)
  private String productPrice;
  @Column(name = "description", length = 225)
  private String productDesc;
  @ManyToOne
  private Category category;
  public int getProductId() {
    return productId;
  }
  public void setProductId(int productId) {
    this.productId = productId;
  }
  public String getProductName() {
    return productName;
  }
  public void setProductName(String productName) {
    this.productName = productName;
  }
  public String getProductPrice() {
    return productPrice;
  }
  public void setProductPrice(String productPrice) {
    this.productPrice = productPrice;
  }
  public String getProductDesc() {
    return productDesc;
  }
  public void setProductDesc(String productDesc) {
    this.productDesc = productDesc;
  }
  public Category getCategory() {
    return category;
  }
  public void setCategory(Category category) {
    this.category = category;
  }
  public Product(int productId, String productName, String productPrice, String productDesc, Category category) {
    super();
    this.productId = productId;
    this.productName = productName;
    this.productPrice = productPrice;
    this.productDesc = productDesc;
    this.category = category;
  }
  public Product() {
    // TODO Auto-generated constructor stub
  }
  @Override
  public String toString() {
    return "Product [productId=" + productId + ", productName=" + productName + ", productPrice=" + productPrice
        + ", productDesc=" + productDesc + ", category=" + category + "]";
  }
  
  
}

Create a hibernate.cfg.xml for configuring the relation and mapping Entity. To learn about this file you can check it here How to configure hibernate in Java application?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/onetomanyanno</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
    
    <mapping class="com.onetomany.entity.Product" />
    <mapping class="com.onetomany.entity.Category" />

  </session-factory>
</hibernate-configuration>

Create a HibernateUtil.java helper class to keep the Session factory object.

package com.onetomany.entity;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
  private static SessionFactory factory;
  public static SessionFactory getFactory(){
    try{
  
  if(factory ==null){
    factory	=	new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
  }
    }catch(Exception e){
      e.printStackTrace();
    }
    return factory;
  }
}

Now, Let us Test the application in Test.java

package com.onetomany;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.onetomany.entity.Category;
import com.onetomany.entity.HibernateUtil;
import com.onetomany.entity.Product;

public class Test {

  public static void main(String[] args) {
    Session session = HibernateUtil.getFactory().openSession();
    Transaction tx = null;
    tx = session.beginTransaction();

    // Create category
    Category category1 = new Category();
    category1.setCategoryName("Mobile");
    category1.setCategoryDesc("We have different types of Mobile");
    session.save(category1);

    // create product
    Product product = new Product();
    product.setProductName("Redmi");
    product.setProductPrice("5000");
    product.setProductDesc("Redmi is a nice company");
    product.setCategory(category1);
    session.save(product);

    Category category2 = new Category();
    category2.setCategoryName("Books");
    category2.setCategoryDesc("We have different types of Books");
    session.save(category2);

    // create product
    Product product2 = new Product();
    product2.setProductName("Wings of Fire");
    product2.setProductPrice("5100");
    product2.setProductDesc("It is a nice book");
    product2.setCategory(category2);
    session.save(product2);
    tx.commit();
    session.close();
  }

}

Now, run this file and see the output. Here, your @OneToMany Mapping will be done. The following output will be shown in the console window

May 06, 2021 12:25:55 PM org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: Table 'onetomanyanno.products' doesn't exist
Hibernate: drop table if exists Category
Hibernate: drop table if exists products
Hibernate: create table Category (id integer not null auto_increment, cdesc varchar(100), cname varchar(100), primary key (id))
Hibernate: create table products (productId integer not null auto_increment, description varchar(225), pname varchar(100), price varchar(100), category_id integer, primary key (productId))
Hibernate: alter table products add index FKC42BD164C91AB3EA (category_id), add constraint FKC42BD164C91AB3EA foreign key (category_id) references Category (id)
May 06, 2021 12:26:02 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: insert into Category (cdesc, cname) values (?, ?)
Hibernate: insert into products (category_id, description, pname, price) values (?, ?, ?, ?)
Hibernate: insert into Category (cdesc, cname) values (?, ?)
Hibernate: insert into products (category_id, description, pname, price) values (?, ?, ?, ?)

Also. view the Tables in your database.

mysql> select * from category;
+----+-----------------------------------+--------+
| id | cdesc                             | cname  |
+----+-----------------------------------+--------+
|  1 | We have different types of Mobile | Mobile |
|  2 | We have different types of Books  | Books  |
+----+-----------------------------------+--------+
2 rows in set (0.00 sec)

mysql> select * from products;
+-----------+-------------------------+---------------+-------+-------------+
| productId | description             | pname         | price | category_id |
+-----------+-------------------------+---------------+-------+-------------+
|         1 | Redmi is a nice company | Redmi         | 5000  |           1 |
|         2 | It is a nice book       | Wings of Fire | 5100  |           2 |
+-----------+-------------------------+---------------+-------+-------------+
2 rows in set (0.00 sec)

Thus, this is how we implement the @OneToMany relationship in Hibernate using annotaion.