Friday, August 2, 2013

Hibernate One To One Bidirectional Mapping with Annotations

Assumption : Lecturer can teach only one Course and the given Course can be taught only by one lecturer.  therefore we will use One To One mapping here

Lecturer.java


package com.chathurangaonline.examples.model;

import javax.persistence.*;

@Entity
@Table(name = "Lecturer")
public class Lecturer {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

    @OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL,optional=false)
    @JoinColumn(name = "course_id")
    private Course course;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }

}




Course.java

package com.chathurangaonline.examples.model;

import javax.persistence.*;

@Entity
@Table(name = "Course")
public class Course {

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

    @Column(name = "course_name")
    private String courseName;

    @OneToOne(mappedBy = "course",fetch = FetchType.LAZY)
    private Lecturer lecturer;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public Lecturer getLecturer() {
        return lecturer;
    }

    public void setLecturer(Lecturer lecturer) {
        this.lecturer = lecturer;
    }
}



you will see that there is a mapping relationship between Lecturer and Course entities. this relationship is  bidirectional mapping relationship because each entity contain the reference for other entity. in bidirectional relationship, one entity will manage and own the foreign key relationship. it is the entity that holds the forien key too.

what is mappedBy atrribute?

as i have described above, in bidirectional relationship one entity will own  and manage the foreign key relationship. the other entity (which does not manage the foreign key) uses the mappedBy attribute to tell that who is the owner of the foreign key relationship.

    @OneToOne(mappedBy = "course",fetch = FetchType.LAZY)
    private Lecturer lecturer;

 in this example, mappedBy attributes says that "Hey, i am not the owner of the foreign key and i do not manage it.  it is owned and managed by the course attribute belongs to the Lecturer entity.


Hope this will helpful for you.

Cheers
Chathuranga Tennakoon
www.chathurangaonline.com

No comments:

Post a Comment