Hibernate One to Many Relationship



According to database terminology, one row of one table related with multiple
rows of other table.

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


I mean, one [Parent] to many [Children], one [Teacher] to many [Student], example of oneto-
many is some thing category books contains different type of books, one vendor contains
lot of customers etc.


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
eitherSet,List,Map.
In the mapping file of that parent POJO class, we need to configure the collection.


We will use following files:
Parent.java [POJO class]
Parent.hbm.xml
Children.java [POJO class]
Children.hbm.xml
hibernate.cfg.xml
HibernateEngine.java


Queries 
CREATE TABLE PARENTS_DATA (PARENT_ID INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20))

CREATE TABLE CHILDREN_DATA (CHILD_ID INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(20),AGE INT,PARENT_ID INT) 


Parent.java
@Entity
@Table(name="PARENTS_DATA")

public class Parent {


@Id
@GeneratedValue(strategy=IDENTITY)

@Column(name="PARENT_ID")
private int id=0;


@Column(name="NAME")
private String name;


@OneToMany(fetch=FetchType.LAZY, targetEntity=Children.class,
cascade=CascadeType.ALL)

@JoinColumn(name="PARENT_ID",referencedColumnName="PARENT_ID")
private Set children; 


// provide set and get method of all members

}

Children.java
@Entity
@Table(name="CHILDREN_DATA")

public class Children {


@Id
@GeneratedValue
@Column(name="CHILD_ID")

private int id;


@Column(name="NAME")
private String name;


@Column(name="AGE")
private int age;


// provide set and get for all members
}


HibernateEngine.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateEngine {


public static void main(String[] javaPlanet)
{


Configuration condigurationObj = new Configuration();       condigurationObj.configure("hibernate.cfg.xml"); 
           
SessionFactory factoryObj = condigurationObj.buildSessionFactory();            
Session sessionObj = factoryObj.openSession();         

Parent parentObj=new Parent();       
parentObj.setName("Karna");

Children childObj1=new Children();      

childObj1.setName("Abhi");      
childObj1.setAge(11);      
childObj1.setParentObj(parentObj);
 

Children childObj2=new Children();       

childObj2.setName("Adi");       
childObj2.setAge(10);      
childObj2.setParentObj(parentObj);      

Set<Children> childSet = new HashSet<Children>();
childSet.add(childObj1);
childSet.add(childObj2);
parentObj.setChildren(childSet);

 
Transaction transaction=sessionObj.beginTransaction();       

sessionObj.save(parentObj);        
transaction.commit();             

sessionObj.close();      
factoryObj.close();
 
}