Wednesday, July 17, 2013

Difference between Unidirectional and Bidirectional mapping in hibernate


Unidirectional Mapping

When only one of the pair of entities contains a reference to the other, the association is unidirectional. for example, assume that there are two entities called Lecturer and Course.

In unidirectional mapping, the lecturer will hold a reference for the course OR course will hold a reference for the lecturer.(Not Both) It is mandatory that the references should not be mapped to the both directions and there should be only one direction(unidirectional) mapping.

In unidirectional mapping, it will provide the navigational access only to one direction.

eg:-

assumption: lecturer can teach only once course and a given course can be taught only by one lecturer

unidirectional mapping  from lecturer to course

class Lecturer{

   private Long id;
   private  String lecturerName;
   private Course;

   //getter and setters
}


class Course{
 
   private Long id;
   private String courseName;

    //getter and setters
}


unidirectional mapping  from course to lecturer


class Lecturer{

   private Long id;
   private  String lecturerName;


   //getter and setters
}


class Course{
 
   private Long id;
   private String courseName;
   private Lecturer lecturer;

    //getter and setters
}



Bidirectional Mapping

if the association between both entities are mutual, then it is known as bidirectional mapping. in bidirectional mapping, the lecturer should hold to a reference for the course and the same time the course should a reference to the lecturer.

therefore in bi-directional mapping, it will provide the navigational access to the both directions.

eg:-
assumption: lecturer can teach only once course and a given course can be taught only by one lecturer

class Lecturer{

   private Long id;
   private  String lecturerName;
   private Course;

   //getter and setters
}


class Course{
 
   private Long id;
   private String courseName;
   private Lecturer lecturer;

    //getter and setters
}


hope this will help for you!

Cheers
Chathuranga Tennakoon
www.chathurangaonline.com


No comments:

Post a Comment