Hibernate mapping annotations

In this section, you will learn about the annotations used for various mapping in Hibernate.

Hibernate mapping annotations

Hibernate mapping annotations

In this section, you will learn about the annotations used for various mapping in Hibernate.

Given below mapping annotations under different type of mapping :

One-to-One Mapping

The worker and workerdetail have one-to-one mapping which can be symbolically shown as below :

worker----------------->workerdetail

In Worker class, do the following mapping :


@OneToOne(mappedBy = "worker", cascade = CascadeType.ALL)
private WorkerDetail workerDetail;

In WorkerDetail class, do the following mapping :


@OneToOne
@PrimaryKeyJoinColumn
private Worker worker;

One-to-Many Mapping

The employee and address table have One-to-Many relation as follows :

The Address class should have following mapping annotation :


@OneToMany(mappedBy = "address")
private Set<Employee> employees;

The mapping annotation of Employee class are given below :


@OneToMany(mappedBy = "address")
private Set<Employee> employees;

Many to Many Mapping

Many student may have register for various courses  and a course may have many registered student. The Many to Many mapping between student and course table can be shown as follows:

The mapping annotation of Student class is given below:


@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name="student_course",joinColumns={@JoinColumn(name="student_id")},inverseJoinColumns={@JoinColumn(name="course_id")})
private Set<Course> courses = new HashSet<Course>();

The Course class mapping annotation is given below :


@ManyToMany(mappedBy="courses")
private Set<Student> students = new HashSet<Student>();

NOTE : student_course table doesn't have pojo class neither it have mapping annotation needed in the above cases.