Get all updates of Java4s
Follow Us: Email Newsletter

Hibernate One to Many Mapping Insert Query Example

Hibernate » On Jul 22, 2011 { 33 Comments } By Sivateja

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

[or]

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…

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

 

Vendor.java

Customer.java

Customer.hbm.xml

Vendor.hbm.xml

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

hibernate.cfg.xml

OurLogic.java

Notes:

  • In Vendor.java, we have taken a property of type Set
  • In Customer.java, 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 Author ♦

Java4s_Author
sivateja@java4s.com
Full Stack( Java/J2EE & UI/UX ) Developer and founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog. Sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

33 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:

    @Geetha

    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. MR Chowdari says:

    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. vijaya kumar says:

    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(SQLStateConverter.java:103)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
    Exception ==>Could not execute JDBC batch update
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
    at OneToOneMain.main(OneToOneMain.java:67)
    Caused by: java.sql.BatchUpdateException: Field ‘CUSTOMER_ID’ doesn’t have a default value
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1666)
    at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1082)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
    … 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) {
    this.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;
    }

    }

    org.hibernate.dialect.Oracle10gDialect
    jdbc:oracle:thin:@localhost:1521:orcl
    system
    system
    oracle.jdbc.driver.OracleDriver
    true
    update

    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();
    cfg.configure(“hibernate.cfg.xml”);

    SessionFactory factory = cfg.buildSessionFactory();

    Session session = factory.openSession();

    Person p = new Person();
    p.setPersonid(101);
    p.setName(“debu”);

    Address d = new Address();
    d.setAddressid(300);
    d.setAddressname(“dangechowk”);

    Address d1 = new Address();
    d.setAddressid(301);
    d.setAddressname(“nigdi”);

    Address d2 = new Address();
    d.setAddressid(302);
    d.setAddressname(“bhoomkar”);

    Set s = new HashSet();
    s.add(d);
    s.add(d1);
    s.add(d2);

    p.setChild(s);

    Transaction tx = session.beginTransaction();

    session.save(p);

    tx.commit();
    session.close();
    System.out.println(“One To Many is Done..!!”);
    factory.close();

    }

    }

  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:

    sir,
    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 Customer.java I looked here
    http://www.tutorialspoint.com/hibernate/hibernate_one_to_many_mapping.htm
    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.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
What would you like to learn today?
Browse these popular technologies
Hibernate spring struts Servlets ajax Log4j jQuery Json Core Java Web Services AngularJs
Most Recent Tutorials
Hibernate_Logo Hibernate Recent Posts Spring_Logo Spring Recent Posts Struts_Logo Struts Recent Posts
Useful Links Current & UpComing Tutorials
Upcoming
  Web Services [ SOAP ], JSP
Contact | About Us | Privacy Policy | Advertise With Us

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