Newsletter |
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
[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
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; } }
Customer.java
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; } }
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"/> <property name="forevenId" column="forevenid" insert="false" /> </class> </hibernate-mapping>
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"/> <set name="children" cascade="all" > <key column="forevenid" /> <one-to-many class="str.Customer" /> </set> </class> </hibernate-mapping>
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
<?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 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(); cfg.configure("hibernate.cfg.xml"); SessionFactory factory = cfg.buildSessionFactory(); Session session = factory.openSession(); //parent object Vendor v =new Vendor(); v.setVendorId(101); v.setVendorName("java4s"); //creating 3 child objects Customer c1=new Customer(); c1.setCustomerId(504); c1.setCustomerName("customer4"); Customer c2=new Customer(); c2.setCustomerId(505); c2.setCustomerName("customer5"); Customer c3=new Customer(); c3.setCustomerId(506); c3.setCustomerName("customer6"); // adding child objects to set, as we taken 3rd property set in parent Set s=new HashSet(); s.add(c1); s.add(c2); s.add(c3); v.setChildren(s); Transaction tx = session.beginTransaction(); session.save(v); tx.commit(); session.close(); System.out.println("One To Many is Done..!!"); factory.close(); } }
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 the Author .:: | ||
Comments
40 Responses to “Hibernate One to Many Mapping Insert Query Example”
very good site with good examples. easy to understand
@Geetha
Glad to hear your feedback 🙂
really good example….
@Chandan Modi
Thank you 🙂
good site
nice straight forward example
hi
it is very easy and traight forward to understand.
Very good and easy to understand..Its damn damn simple!!
u guys are dng great job!!!
This site is excellent boss . I am proud to be the client of this site.
How to write hibernate mapping in a single hbm.xml file for two different table with one Pojo class.
Awesome tutorials..simply struggling with tutorialspoint, javatpoint tutorials..this one is really good for beginners,,,thanks sivateja for coming down and keeping it simple
Excellent especially hibernate looks like very simple to me..Tq
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
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
Hi can i know what is the use of insert=”false” in customer mapping file
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
very good example for beginners.
very good explanation. easy to understand.
Hi nice one …………….good for me i m beginner in java
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.:)
please tell guide how i insert data into database using hibernate + set interface????
“insert=false” why this?pls… explain
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
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.
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
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.
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();
}
}
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…….
I think you has given duplicate values in your Address. Check your Address Table Once
sir,
please tell me how can you make foreign key on forevenId column in customer table without forevenid column in a vendor.
ORA-02291: integrity constraint (SYSTEM.FK24217FDEA99AF7EF)violated – parent key not found
this code raise an error! give me the solution
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.
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
sir this example not getting claer because there is no common property between Vendor and custmor
Data is not inserted in Tables !!!
There is one problem with this example.
We have to add session.save(v) statement After Vendor object creation(line number 25).
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.
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?
Sir I request to u kindly make the session on Angular Js and enable links Thanks