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; @Entity private int collegeId; @Id @Column(name=”collegeName”) @OneToMany(targetEntity=Student.class,mappedBy=”college”,cascade=CascadeType.ALL,fetch=FetchType.EAGER) } |
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 private int studentId; @ManyToOne @Id @Column(name=”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; AnnotationConfiguration config=new AnnotationConfiguration(); College college1= new College(); s1.setCollege(college1); ArrayList list=new ArrayList(); college1.setStudent(list); session.save(college1); tx.commit(); } |
See Many to Many relation also
facebook layouts says
February 16, 2011 at 1:52 amthnx bro
Breana Kjolseth says
May 29, 2011 at 10:45 pmMy cousin recommended this blog and she was totally right keep up the fantastic work!
Ezhil says
January 18, 2012 at 7:43 pmnice work
Bhanuchander says
June 17, 2012 at 10:24 pmNice example and easy to understand. Thanks