Newsletter

Hibernate Many to One Mapping Insert Query Example

Hibernate » on Jul 25, 2011 { 16 Comments } By Sivateja

Let us see how to achieve hibernate many to one mapping with insert query, just go through few points before we start the example

  • In the many to one relationship, the relationship is applied from child object to parent object, but in one to may parent object to child object right..! just remember
  • many to one is similar to one to many but with the little changes
  • If we want to apply many to one relationship between two pojo class objects then the following changes are required

In the child pojo class, create an additional property of type parent for storing the parent object in child object [ If you are confused just remember you will be able to understand in the example ], in the child pojo class mapping file we need to write <many-to-one name=””> for parent type property unlike <property name=””>

Example on Many to One With Insert Query

files required

  • Vendor [parent pojo]
  • Customer.java [child pojo]
  • OurLogic.java [our logic]
  • Vendor.hbm.xml
  • Customer.hbm.xml
  • hibernate.cfg.xml

Vendor.java

package str;

public class Vendor {

	private int vendorId;
	private String vendorName;

	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;
	}	

}

Customer.java

package str;
public class Customer {

	private int customerId;
	private String customerName;
	private Vendor parentObjects;

	public Vendor getParentObjects() {
		return parentObjects;
	}
	public void setParentObjects(Vendor parentObjects) {
		this.parentObjects = parentObjects;
	}
	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;
	}
}

Vendor.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="str.Vendor" table="vendor">

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

</class>
</hibernate-mapping>

Customer.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="str.Customer" table="customer">

<id name="customerId" column="custid"  />
<property name="customerName" column="custname" length="10"/>
<many-to-one name="parentObjects" column="Vdummy" class="str.Vendor" cascade="all" />

</class>
</hibernate-mapping>

hibernate.cfg.xml

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

<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@www.java4s.com:1521:XE</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="hbm2ddl.auto">update</property>

<mapping resource="Customer.hbm.xml"></mapping>
<mapping resource="Vendor.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>

OurLogic.java

package str;

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

		SessionFactory factory = cfg.buildSessionFactory();
		Session session = factory.openSession();		

		Vendor v =new Vendor();

		            v.setVendorId(101);
		            v.setVendorName("java4s");

		 Customer c1=new Customer();

		             c1.setCustomerId(504);
		             c1.setCustomerName("customer4");
		             c1.setParentObjects(v);

		 Customer c2=new Customer();

		             c2.setCustomerId(505);
		             c2.setCustomerName("customer5");
		             c2.setParentObjects(v);

         Customer c3=new Customer();

		             c3.setCustomerId(506);
		             c3.setCustomerName("customer6");
		             c3.setParentObjects(v);           		             

		    Transaction tx = session.beginTransaction();

		                      session.save(c1);
		                      session.save(c2);
		                      session.save(c3);

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

	}
}

Notes:

  •  In line numbers 28,34,40 we are adding parent to child object
  • In line number 44,45,46 we are saving all child objects,  but you know some thing, according to this code at line number 45, first child object will be saved with the parent,  at 45,46 just child (customer object) only will be saved as parent is saved already

 

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
- 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.

Comments

16 Responses to “Hibernate Many to One Mapping Insert Query Example”
  1. Vivek says:

    please tell me about the column you used in customer.hbm.xml.

    at

    https://www.java4s.com/hibernate/hibernate-many-to-one-mapping-insert-query-example/

    and in which table we need to create this column and with what type of constraints.

    i am stuck at that point.

    Thanks

  2. Java4s says:

    @Vivek

    Vendor primary key will be stored in VDUMMY column of customer table.
    Output of above application will be llke

    SQL> select * from customer;

    CUSTIDCUSTNAMEVDUMMY
    504 customer4 101
    505 customer5 101
    506 customer6 101

    SQL> select * from vendor;

    VENDIDVENDNAME
    101 java4s
  3. Anand says:

    Sir..In the many-to-one mapping you have missed the class name i.e. ‘str.Vendor'(in Customer.hbm.xml line no 11)
    https://www.java4s.com/hibernate/hibernate-many-to-one-mapping-insert-query-example/

    I think you should correct that…

  4. Java4s says:

    @Anand

    Yeah you are correct, that should contain class name too its corrected now. Thanks for the update.

    Every time we are facing this problem 🙂 my syntax script ignoring class attribute some times, however we have correct code in downloaded example, any time if you got this type of doubt please check with the downloaded one.

    Thanks lotz Anand.

  5. hi Java4s team,

    this is raju kapadne ,by reading this many to one concept , i got clearly many to one relationship thanks for that.

  6. Saleem says:

    Thank u for giving such a wonderful material …Thanks alot

  7. suvarna says:

    very nice tutorial……

  8. karthick says:

    why vdummy column of customer table contains the value of v.setVendorId(101)
    instead of v.setVendorName(“java4s”) value…can it store vendorname insted of vendorid
    pls clear my doubt sir….

  9. karthick says:

    should we define vdummy column as a foreign key column?
    pls clear my doubt…

  10. shrikanth reddy says:

    thanks a lot for such a easy and nice material…..

  11. shrikanth reddy says:

    how to get vname in customer table for that again we need to create extra coloum or what please clear my doubt…..

  12. Shyam Vaddepally says:

    why vdummy column of customer table contains the value of v.setVendorId(101)
    instead of v.setVendorName(“java4s”) value…can it store vendorname insted of vendorid
    pls clear my doubt sir….

    should we define vdummy column as a foreign key column?
    pls clear my doubt…

  13. pavan says:

    what is the main difference between one-to-many relationship and many-to-one relationship

    and at what situations it will be use.

  14. immaniyelu says:

    Sir, in many to one we took reference variable in child pojo class.can we take reference variable as collection type or not?

  15. Arun Bharathi says:

    Sir,

    Small correction in notes(2nd point). You mention line number 45 will save child object with parent object.

    But actually it is line number 44.

  16. san says:

    Hi, Awesome tut about association.

    But at line no 50 please print Many to One is done otherwise it will confuse the freshers

Name*
Mail*
Website



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 - 2018 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.