In this tutorials, we are going to implement hibernate one to many relationship using annotations. In the previous tutorial, we did the same example using xml configuration one to many relationship with xml.

A one to many relationship can occur, if an entity is related to multiple occurrences in another entity. In simple terms, if one row in database table can be mapped to multiple rows in another table, then we can call that relationship as one to many relationship. Here is the example for Hibernate one to many relationship using annotations.

Hibernate One To Many Annotations Example:

To implement the one to many relationship, we are taking Vendor and Customer. Here the relationship between the Vendor to Customer is one to many. That is one Vendor can have multiple Customers. The same relationship is developed using hibernate one to many annotations.

Database Tables :

SQL Tables
CREATE TABLE `vendor` (
`vendid` INT(11) NOT NULL,
`venName` VARCHAR(10) NULL DEFAULT NULL,
PRIMARY KEY (`vendid`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;

CREATE TABLE `customer` (
`custid` INT(11) NOT NULL,
`custaddress` VARCHAR(10) NULL DEFAULT NULL,
`custname` VARCHAR(10) NULL DEFAULT NULL,
`venid` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`custid`),
INDEX (`venid`),
CONSTRAINT FOREIGN KEY (`venid`) REFERENCES `vendor` (`vendid`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;

Project Structure :

Hibernate one to many annotations

Required Dependencies :

pom.xml
<dependencies>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.0.Final</version>
        </dependency>
        <!-- MySQL Driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.0.5</version>
        </dependency>
</dependencies>

Hibernate POJO Classes :

Vendor.java

Vendor.java
package com.onlinetutorialspoint.hibernate.pojo;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "vendor")
public class Vendor {
    @Id
    @Column(name = "vendid")
    private int vendorId;

    @Column(name = "venName", length = 10)
    private String vendorName;

    @OneToMany(targetEntity = Customer.class, cascade = CascadeType.ALL)
    @JoinColumn(name = "venid", referencedColumnName = "vendid")
    private Set customers;

    public int getVendorId() {
        return vendorId;
    }

    public void setVendorId(int vendorId) {
        this.vendorId = vendorId;
    }

    public String getVendorName() {
        return vendorName;
    }

    public void setVendorName(String vendorName) {
        this.vendorName = vendorName;
    }

    public Set getCustomers() {
        return customers;
    }

    public void setCustomers(Set customers) {
        this.customers = customers;
    }

}

Customer.java

Customer.java
package com.onlinetutorialspoint.hibernate.pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer {
    @Id
    @Column(name = "custid")
    private int customerId;

    @Column(name = "custname", length = 10)
    private String customerName;

    @Column(name = "custaddress", length = 10)
    private String customerAddress;

    public int getCustomerId() {
        return customerId;
    }

    public void setCustomerId(int customerId) {
        this.customerId = customerId;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getCustomerAddress() {
        return customerAddress;
    }

    public void setCustomerAddress(String customerAddress) {
        this.customerAddress = customerAddress;
    }

}

Hibernate Utility Class :

HibernateUtil.java

HibernateUtil.java
package com.onlinetutorialspoint.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private HibernateUtil() {

    }

    private static SessionFactory sessionFactory;

    public static synchronized SessionFactory getInstnce() {

        if (sessionFactory == null) {
            Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties());
            sessionFactory = configuration.buildSessionFactory(builder.build());
        }
        return sessionFactory;

    }
}

Well ! Its completed, Now we can Run our application:

Main.java

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

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

import com.onlinetutorialspoint.hibernate.pojo.Customer;
import com.onlinetutorialspoint.hibernate.pojo.Vendor;
import com.onlinetutorialspoint.util.HibernateUtil;

public class Main {

    public static void main(String a[])
    {
        SessionFactory sessionFactory = HibernateUtil.getInstnce();
        Session session = sessionFactory.openSession();    

        Vendor vendor=new Vendor();
        vendor.setVendorId(101);
        vendor.setVendorName("IBM");

        Customer customer=new Customer();
        customer.setCustomerId(102);
        customer.setCustomerName("NIFY");
        customer.setCustomerAddress("BANG");

        Customer customer2=new Customer();
        customer2.setCustomerId(104);
        customer2.setCustomerName("TCS");
        customer2.setCustomerAddress("HYD");

        Customer customer3=new Customer();
        customer3.setCustomerId(105);
        customer3.setCustomerName("VERIZON");
        customer3.setCustomerAddress("US");

        Set customers = new HashSet();
        customers.add(customer);
        customers.add(customer2);
        customers.add(customer3);

        vendor.setCustomers(customers);

        Transaction transaction=session.beginTransaction();

        session.save(vendor);

        transaction.commit();

        session.close();
        sessionFactory.close();
    }

}

Output :

Terminal
Hibernate: select customer_.custid, customer_.custaddress as custaddr2_0_, customer_.custname as custname3_0_ from customer customer_ where customer_.custid=?
Hibernate: select customer_.custid, customer_.custaddress as custaddr2_0_, customer_.custname as custname3_0_ from customer customer_ where customer_.custid=?
Hibernate: select customer_.custid, customer_.custaddress as custaddr2_0_, customer_.custname as custname3_0_ from customer customer_ where customer_.custid=?
Hibernate: insert into vendor (venName, vendid) values (?, ?)
Hibernate: insert into customer (custaddress, custname, custid) values (?, ?, ?)
Hibernate: insert into customer (custaddress, custname, custid) values (?, ?, ?)
Hibernate: insert into customer (custaddress, custname, custid) values (?, ?, ?)
Hibernate: update customer set venid=? where custid=?
Hibernate: update customer set venid=? where custid=?
Hibernate: update customer set venid=? where custid=?

Database Output :

Hibernate one to many annotations output

Happy Learning:)

Download Example