October 22, 2014

One To Many mapping using Hibernate

In this example we have two tables , Student and College.Each college has many students. And many Students have one college. This is a classic example of one to many relation

College table has two attributes

CollegerID
CollegeName

And Student table has the following attributes

StudentId 
StudentName 
collegeId 

Let us create the mapping for the above table COLLEGE and see how the relation can be made.

package oneToMany;

import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name=”COLLEGE”)
public class College {

private int collegeId;
private String collegeName;
private List student;

@Id
@GeneratedValue
public int getCollegeId() {
return collegeId;
}
public void setCollegeId(int collegeId) {
this.collegeId = collegeId;
}

@Column(name=”collegeName”)
public String getCollegeName() {
return collegeName;
}
public void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}

@OneToMany(targetEntity=Student.class,mappedBy=”college”,cascade=CascadeType.ALL,fetch=FetchType.EAGER)
public List getStudent() {
return student;
}
public void setStudent(List student) {
this.student = student;
}

}

Here you can notice that we have created an object of the personDetail class and on top of the getter method we annoted as oneToMany

We have certain parameters for oneToMany annotation
1) targetEntity

Here we need to specify the class which we need to make the relation. In our example we are giving Student class

2) mappedBy

 mapped by defines how he college class  is mapped with student

3) cascadeType

If you want to rempove the data from personDetails while removing data from person we can select cascadeType.REMOVE,

same way to refresh the data from personDetails while refresing data in the person we can select cascadeType.REFRESH .

Likewise we have different cascadeTypes

1. ALL
2. MERGE
3. PERSIST
4. REFERESH
5. REMOVE
Instead of selecting each and every one of these we can select ALL
ie, If we delete a college, the corresponding record should be deleted from student table,

4) Fetch
There is another property called Fetch, FetchType can have values either EAGER or LAZY
If we select EAGER , while fetching the person record, the corresponding record of the personDetails also get loaded
By default fetchType for OneToMany mapping is LAZY. But for oneToOne default type is EAGER
Now let’s create the class for the entity STUDENT

  package oneToMany;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name=”STUDENT”)
 public class Student {

private int studentId;
private String studentName;
private College college ;

@ManyToOne
@JoinColumn(name=”collegeId”)
public College getCollege() {
return college;
}
public void setCollege(College college) {
this.college = college;
}

@Id
@GeneratedValue
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}

@Column(name=”studentName”)
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}

}

1) joincolumn- this is the name for the join column, In our example we are giving collegeId

Now let’s see how can we insert data into these tables using the client code

  package oneToMany;

import java.util.ArrayList;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
public class testHibernate {
public static void main(String[] args) {

AnnotationConfiguration config=new AnnotationConfiguration();
config.addAnnotatedClass(College.class);
config.addAnnotatedClass(Student.class);
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx=session.beginTransaction();

College college1= new College();
college1.setCollegeName(“NewYork College”);Student s1=new Student ();
s1.setStudentName(“Joseph”);Student s2=new Student ();
s2.setStudentName(“Ann”);

s1.setCollege(college1);
s2.setCollege(college1);

ArrayList list=new ArrayList();
list.add(s1);
list.add(s2);

college1.setStudent(list);

session.save(college1);

tx.commit();
}

  }

 

See Many to Many  relation  also

Comments

  1. thnx bro

  2. My cousin recommended this blog and she was totally right keep up the fantastic work!

  3. nice work

  4. Bhanuchander says:

    Nice example and easy to understand. Thanks

Leave a Reply