Hibernate One To Many Annotations | Hibernate Annotations | @OnetoMany

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
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.
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 :
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 :
Required Dependencies :
<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
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
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
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
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 :
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 :
Happy Learning:)


Hibernate One To Many Annotations Example

File size: 18 KB
Downloads: 1062


Many to One Mapping in Hibernate Example
Hibernate Table per Class strategy Annotations Example
Hibernate One To Many Example (XML Mapping)
Hibernate Right Join Example
Hibernate Left Join Example
Hibernate 4 Example with Annotations Mysql
Custom Generator Class in Hibernate
Hibernate Filters Example Annotation
Hibernate Named Query with Example
@Formula Annotation in Hibernate Example
One to One Mapping in Hibernate using foreign key (XML)
Basic Hibernate Example with XML Configuration
Hibernate One to One Mapping using primary key (XML)
Singleton Hibernate SessionFactory Example
Calling Stored Procedures in Hibernate

Many to One Mapping in Hibernate Example
Hibernate Table per Class strategy Annotations Example
Hibernate One To Many Example (XML Mapping)
Hibernate Right Join Example
Hibernate Left Join Example
Hibernate 4 Example with Annotations Mysql
Custom Generator Class in Hibernate
Hibernate Filters Example Annotation
Hibernate Named Query with Example
@Formula Annotation in Hibernate Example
One to One Mapping in Hibernate using foreign key (XML)
Basic Hibernate Example with XML Configuration
Hibernate One to One Mapping using primary key (XML)
Singleton Hibernate SessionFactory Example
Calling Stored Procedures in Hibernate
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache