• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

One To Many mapping using Hibernate

January 24, 2011 By j2eereference 4 Comments

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

Related Posts

  • First level caching in Hibernate
  • Hibernate – Query By Criteria
  • Hibernate Query Language
  • Many to Many mapping in hibernate
  • one to one mapping using Hibernate
  • Implementing composite primary key with JPA and Hibernate
  • How to implement primary key with JPA and Hibernate
  • What is Hibernate?

Filed Under: Hibernate

Reader Interactions

Comments

  1. facebook layouts says

    February 16, 2011 at 1:52 am

    thnx bro

    Reply
  2. Breana Kjolseth says

    May 29, 2011 at 10:45 pm

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

    Reply
  3. Ezhil says

    January 18, 2012 at 7:43 pm

    nice work

    Reply
  4. Bhanuchander says

    June 17, 2012 at 10:24 pm

    Nice example and easy to understand. Thanks

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.