Hibernate One to Many Mapping Insert Query Example

Hibernate » on Jul 22, 2011 { 40 Comments } By Sivateja

One-to-Many:  according to database terminology, one row of table related with multiple rows of other table


According to hibernate, one object of one pojo class related to multiple objects of other pojo

I mean, one [parent] to many [Children], example of one-to-many is some thing category books contains different type of books, one vendor contains lot of customers bla bla.

To achieve one-to-many between two pojo classes in the hibernate, then the following two changes are required

  • In the parent pojo class, we need to take a collection property, the collection can be either Set,List,Map (We will see the example on separate collection later)
  • In the mapping file of that parent pojo class, we need to configure the collection

I will take this vendor-customer as an example..

Hibernate One-To-Many Insert Query

files required…

  • [pojo class]
  • [pojo class]
  • Customer.hbm.xml
  • hibernate.cfg.xml
  • Vendor.hbm.xml

package str;

import java.util.Set;

public class Vendor {

private int vendorId;
private String vendorName;
private Set children;

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 getChildren() {
return children;
public void setChildren(Set children) {
this.children = children;


package str;
public class Customer {

private int customerId;
private String customerName;
private int forevenId;

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 int getForevenId() {
return forevenId;
public void setForevenId(int forevenId) {
this.forevenId = forevenId;



<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<class name="str.Customer" table="customer">

<id name="customerId" column="custid"  />
<property name="customerName" column="custname" length="10"/>

<property name="forevenId" column="forevenid"  insert="false" />



<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<class name="str.Vendor" table="vendor">

<id name="vendorId" column="vendid"  />
<property name="vendorName" column="vendname" length="10"/>

<set name="children" cascade="all" >

<key column="forevenid" />
<one-to-many class="str.Customer" />



See line number 12,  this time i used one new attribute cascade=”all” we will see about this attribute later as separate topic.


<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
<property name="connection.url"></property>
<property name="connection.username">system</property>
<property name="connection.password">admin</property>

<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="">update</property>

<mapping resource="Customer.hbm.xml"></mapping>
<mapping resource="Vendor.hbm.xml"></mapping>

package str;

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

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

public class OurLogic {

public static void main(String args[])

Configuration cfg = new Configuration();

SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
//parent object
Vendor v =new Vendor();


//creating 3 child objects
Customer c1=new Customer();


Customer c2=new Customer();


Customer c3=new Customer();


// adding child objects to set, as we taken 3rd property set in parent
Set s=new HashSet();



Transaction tx = session.beginTransaction();;

System.out.println("One To Many is Done..!!");



  • In, we have taken a property of type Set
  • In, we have taken one property forevenId of type int to insert Vendor id

In the database

Regarding Vendor.hbm.xml

  • In this mapping file, we used a collection configuration element (Set), because in pojo class of vendor, we used the collection type as Set, (we can use Map,List too)
  • In order to transfer 0perations on parent object to child object we need to add cascade attribute
  • By default, cascade value is none, it means even though relationship is exist, the operations we are doing on parent will not transfer to child, i mean to say here operations are insert, delete, update
  • In our Vendor.hbm.xml,  we used cascade =”all” means all operations at parent object will be transfer to child
  • while applying relationships, we need to configure the foreign key column name, by using which the relationship is done
  • Inthe mapping file, we need to use <key /> eliment to configure foregin key column name, in this example forevenid is foreign key
  • <one-to-many> is child class with which relation been done,  in our example str.Customer is the class [str is the package]



You Might Also Like

  ::. About the Author .::

Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.


40 Responses to “Hibernate One to Many Mapping Insert Query Example”
  1. Geetha says:

    very good site with good examples. easy to understand

  2. java4s says:


    Glad to hear your feedback 🙂

  3. chandan modi says:

    really good example….

  4. Java4s says:

    @Chandan Modi

    Thank you 🙂

  5. hellboy says:

    nice straight forward example

  6. hi

    it is very easy and traight forward to understand.

  7. Niket says:

    Very good and easy to understand..Its damn damn simple!!

  8. Ravi says:

    u guys are dng great job!!!

  9. Nooka says:

    This site is excellent boss . I am proud to be the client of this site.

  10. shiffy says:

    How to write hibernate mapping in a single hbm.xml file for two different table with one Pojo class.

  11. Rajesh says:

    Awesome tutorials..simply struggling with tutorialspoint, javatpoint tutorials..this one is really good for beginners,,,thanks sivateja for coming down and keeping it simple

  12. Manoj says:

    Excellent especially hibernate looks like very simple to me..Tq

  13. Excellent It’s very good for Freshers as well as for Exp. great job once go through this site life make easy for who feel afraid of programming grwat job

  14. madhukar says:

    Its very good website and easy to understand, thank’s bro
    How we download, I want total material of hibernate and struts, plse provide the dat copies

  15. Hi can i know what is the use of insert=”false” in customer mapping file

    • Abhilash says:

      its because, we dont insert a int value to forevenid in main logic class, so we provide insert=”false”. If you dont provide it then it will look for the forevenid value in main

  16. krishna says:

    very good example for beginners.

  17. laxmi says:

    very good explanation. easy to understand.

  18. Chetan says:

    Hi nice one …………….good for me i m beginner in java

  19. Chetan says:

    Hi Can we have multiple Session-Factory for a single hibernate-cfg.xml file.
    If it is possible could you please post and it not possible which exception we will get if will try to configure it.
    Thanks in advance.:)

  20. chetan says:

    please tell guide how i insert data into database using hibernate + set interface????

  21. karthick says:

    “insert=false” why this?pls… explain

  22. Raghava says:

    hi siva, nice job. i got small doubt.
    Q>regarding pojo and table fields.

    whats the importance or use of this 12 line in customer.hbm.xml.

    does my pojo class exactly represent all the columns of my table?
    thanks in advance man.
    sincerely raghu

  23. Ashish says:

    No doubt the contents are nice but there is no database scripts for the table and it will be difficult to create table according to the examples given by you. So what I would like to suggest is that please provide the database scripts with examples.

  24. Sarath Gowd Thota says:

    on doing this example i am getting following exception :
    I am thinking this is because of my sql db and table creation.
    Can u help me in creating tables.
    org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(
    at org.hibernate.exception.SQLStateConverter.convert(
    at org.hibernate.exception.JDBCExceptionHelper.convert(
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(
    at org.hibernate.engine.ActionQueue.executeActions(
    at org.hibernate.engine.ActionQueue.executeActions(
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(
    at org.hibernate.impl.SessionImpl.flush(
    at org.hibernate.impl.SessionImpl.managedFlush(
    Exception ==>Could not execute JDBC batch update
    at org.hibernate.transaction.JDBCTransaction.commit(
    at OneToOneMain.main(
    Caused by: java.sql.BatchUpdateException: Field ‘CUSTOMER_ID’ doesn’t have a default value
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(
    at com.mysql.jdbc.PreparedStatement.executeBatch(
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(
    … 8 more

  25. seshu says:

    Hi Shiva Thank u for providing such a useful information.

    i have doubt if we are not using mappings(one to one, one to many etc…) in our applications what will be the effect?

    If any one knows the ans please let me know. Thanks in advance.

  26. seema says:

    hi ,I am getting this exception
    Exception in thread “main” org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [Address#0] while executing following code.

    here is my progam.

    public class Person {

    private int personid;
    private String name;
    private Set child;
    public int getPersonid() {
    return personid;
    public void setPersonid(int personid) {
    this.personid = personid;
    public String getName() {
    return name;
    public void setName(String name) { = name;
    public Set getChild() {
    return child;
    public void setChild(Set child) {
    this.child = child;


    public class Address {

    private int addressid;
    private String addressname;
    private int foreign;
    public int getAddressid() {
    return addressid;
    public void setAddressid(int addressid) {
    this.addressid = addressid;
    public String getAddressname() {
    return addressname;
    public void setAddressname(String addressname) {
    this.addressname = addressname;
    public int getForeign() {
    return foreign;
    public void setForeign(int foreign) {
    this.foreign = foreign;



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

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

    public class OurLogic {

    * @param args
    public static void main(String[] args) {
    // TODO Auto-generated method

    Configuration cfg = new Configuration();

    SessionFactory factory = cfg.buildSessionFactory();

    Session session = factory.openSession();

    Person p = new Person();

    Address d = new Address();

    Address d1 = new Address();

    Address d2 = new Address();

    Set s = new HashSet();


    Transaction tx = session.beginTransaction();;

    System.out.println(“One To Many is Done..!!”);



  27. seema says:

    Hi I m gettng below exception .
    Exception in thread “main” org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [Address#0]

    I am using Person and Address class instead of Vendor and Customer respectively….

    could you please give me solution how to resolve it…….

  28. gaurav says:

    please tell me how can you make foreign key on forevenId column in customer table without forevenid column in a vendor.

  29. kapil says:

    ORA-02291: integrity constraint (SYSTEM.FK24217FDEA99AF7EF)violated – parent key not found
    this code raise an error! give me the solution

  30. pankaj says:

    Do we really need private int forevenId; in I looked here
    and I think we can simply use private int customerId as a key.
    Please let me know If I am getting confuse between these two.
    Need to understand both implementation Thanks In advance.

  31. Umesh says:

    Adding one point, If you will change the sequence of <key> tag and write before <one-to-many> then we will get an exception org.xml.sax.SAXParseException

  32. sagar says:

    sir this example not getting claer because there is no common property between Vendor and custmor

  33. Naveen Gupta says:

    Data is not inserted in Tables !!!

  34. Naveen Gupta says:

    There is one problem with this example.

    We have to add statement After Vendor object creation(line number 25).

  35. Ganapathi Vangapandu says:

    hello sir,
    My mentor giving me one project that one contains Struts2 + Hibernate.actually i am new to this one.i am unable to understand.please teach me.

  36. Rashmikanat Swain says:

    Examples and Explanations are very good but we are facing some issues while doing DML operation on Tables in DB. Could you please provide db scripts for example?

  37. Mohit says:

    Sir I request to u kindly make the session on Angular Js and enable links Thanks


By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.