Introduction
In many-to-one mapping, various attributes are referred to as one attribute only. In the following example, each employee has just one corporate address, and that address belongs to several employees. We will use annotation to accomplish many-to-one mapping in this case.
Let’s start by learning about the persistent class.
Persistent Classes For One-to-One Mapping
Persistent Classes: Persistent classes in Hibernate are Java classes whose objects or instances will be persisted in database tables. Hibernate performs best when these classes adhere to a few simple conventions, generally known as the Plain Old Java Object (POJO) programming paradigm.
Employee.java and Address.java are two persistent classes in our one-to-one mapping hibernate project. Employee class includes a reference to Address class and vice versa.
Employee.java
package com.codingninjas;
import javax.persistence.*;
@Entity
@Table(name="employee")
public class Employee
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int emp_Id;
private String emp_name,emp_email;
@ManyToOne(cascade=CascadeType.ALL)
private Address emp_address;
public int getemp_Id()
{
return emp_Id;
}
public void setemp_Id(int em_Id)
{
this.emp_Id=emp_Id;
}
public String getemp_name()
{
return emp_name;
}
public void setemp_name(String emp_name)
{
this.emp_name=emp_name;
}
public String getemp_email()
{
return emp_email;
}
public void setemp_email(String emp_email)
{
this.emp_email=emp_email;
}
public Address getemp_address()
{
return emp_address;
}
public void setemp_address(Address emp_address)
{
this.emp_address=emp_address;
}
}
Address.java
package com.codingninjas;
import javax.persistence.*;
@Entity
@Table(name="address")
public class Address
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int address_Id;
private String add_Line1,add_city,add_state,add_country;
private int add_pincode;
@OneToOne(cascade=CascadeType.ALL)
private Employee employee;
public int getaddress_Id()
{
return address_Id;
}
public void setaddress_Id(int address_Id)
{
this.address_Id=address_Id;
}
public String getadd_Line()
{
return add_Line;
}
public void setadd_Line(String add_Line)
{
this.add_Line=add_Line;
}
public String getadd_city()
{
return add_city;
}
public void setadd_city(String add_city)
{
this.add_city=add_city;
}
public String getadd_state()
{
return add_state;
}
public void setadd_state(String add_state)
{
this.add_state=add_state;
}
public String getadd_country()
{
return add_country;
}
public void setadd_country(String add_country)
{
this.add_country=add_country;
}
public int getadd_pincode() {
return add_pincode;
}
public void setadd_pincode(int add_pincode)
{
this.add_pincode=add_pincode;
}
public Employee getemployee()
{
return employee;
}
public void setemployee(Employee employee)
{
this.employee=employee;
}
}





