Updated April 4, 2023
Introduction to Hibernate One to One
“One to One” is a mapping scheme used in hibernate. It is similar to the “one to many”, “many to many” type of mapping in databases. The identifier of “one to one” is that there is one unique column in one table, which is known as “primary key” and is linked as a “foreign key” in another table. Tables linked via this kind of arrangement are known to be in a “one to one” relationship. We will see more about how “one to one” mappings are done using hibernate and the syntaxes used to achieve this functionality.
Syntax
The syntax to have “One to One” mapping using hibernate requires a few settings and files. The stepwise process is given below:
1. Create hibernate model classes: Since two tables are mapped using one to one mapping, the two model classes should be created.
For example, employee.java and department.java.
2. All the JPA and persistence related libraries should be imported into JAVA files.
import javax.persistence.Column;
3. @Entity annotation should be declared and defined in the table in the above model classes.
@Entity
@Table(name = "employee", catalog = "emp")
@UniqueConstraint(columnNames = "Emp_Id") }
4. All related functions should be declared and defined in the files to set the values of unique identities.
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "Emp_Id", unique = true, nullable = false)
5. The function declared above should be called to set and get a unique emp id in return.
public void setEmpId(Integer EmpId)
{this.EmpId = stockId;}
6. The one to one relationship should be maintained.
@OneToOne(fetch = FetchType.LAZY, mappedBy = "employee", cascade = CascadeType.ALL)
7. The primary key defined above should be used as a foreign key in another hibernate model class.
@GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "employee")) @Id @GeneratedValue(generator = "generator") @Column(name = "Emp_Id", unique = true, nullable = false)
8. Then one to one mapping should be defined in another class too. <pre><code class="language-js">@OneToOne(fetch = FetchType.LAZY) @PrimaryKeyJoinColumn</code></pre>
9. Getters and setters should be set here like we did set up in step number 5.
Along with the above steps, you also have to configure an XML file to pass the data between the JAVA EE remote platform to the Database system.
How does One to One Relationship Work in Hibernate?
The “One to One” relation helps link two tables with the help of one key. This key is unique in one table and is present in another table with the same or another name, but the column values remain the same.
There are two tables named “Employee” and “Department”. Every employee works in a particular department. One employee can not work in more than one department. The employee table has its unique identifier “Emp_Id”, and the department table has its primary key as “Dept_Id”. “Dept_Id” acts as a foreign key in the Employee table as every employee is assigned with a unique department Id to establish a relationship. This kind of mapping is known as “One to One” mapping.
Employee table:
Employee |
Emp_Id |
Emp_name |
Emp_DOB |
Dept_Id |
Department table:
Department |
Dept_Id |
Dept_name |
Dept_Desc |
Example
Let us see one example in hibernate:
File 1: Employee.java
Code:
package emp.Employee;
import java.util.Date;
import javax.persistence.*;
import org.hibernate.annotations.*;
@Entity
@Table(name = "Employee", catalog = "emp")
public class Employee implements java.io.Serializable {
private Integer empId;
private String empName;
private string Dept_Id;
@GenericGenerator(name = "generator", strategy = "foreign",
parameters = @Parameter(name = "property", value = "employee"))
@Id
@GeneratedValue(generator = "generator")
@Column(name = "Emp_ID", unique = true, nullable = false)
public Integer getEmpId() {
return this.empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
@Column(name = "Emp_Name", nullable = false, length = 100)
public String getEmpName() {
return this.empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public Employee getDept() {
return this.Dept_id;
}
public void setDept(Employee emp) {
this.Dept_Id = Dept_Id ;
}
}
File 2: Department.java
Code:
package emp.dept;
import javax.persistence.*;
import static javax.persistence.GenerationType.IDENTITY;
@Entity
@Table(name = "Department", catalog = "emp", uniqueConstraints = {
@UniqueConstraint(columnNames = "Dept_Name"),
@UniqueConstraint(columnNames = "Dept_Id") })
public class Department implements java.io.Serializable {
private Integer deptId;
private String deptName;
public Stock(String stockCode) {
this.stockCode = stockCode;
this.stockName = stockName;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "Dept_Id", unique = true, nullable = false)
public Integer getDeptId() {
return this.deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
@Column(name = "Dept_Name", nullable = false, length = 20)
public String getDeptName() {
return this.deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
@OneToOne(fetch = FetchType.LAZY, mappedBy = "Department", cascade = CascadeType.ALL)
}
}
File 3: HelloWorld.java (Execution file)
Code:
package emp.dept;
import java.util.Date;
import org.hibernate.Session;
import emp.dept;
import emp.Employee;
import emp.util.HibernateUtil;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hibernate one to one");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Department dept = new Department();
dept.setEmpId("1");
dept.Name("Test");
Employee emp = new Employee();
emp.setEmpName("ATname");
emp.setEmpId("2")
emp.setDept("1")
session.save(Department);
session.getTransaction().commit();
System.out.println("done");
}
}
Output:
Conclusion
Hibernate “One to One” mapping is a useful tool to establish a “one to one” relationship with the database. There is a big advantage added to having queries building in hibernate. The advantage is that queries can be created irrespective of the database used. So it does not matter if it is oracle’s database or MySQL. The hibernate annotations and queries are independent of the database used. This reduces the overhead of migrating the database dependent applications from one platform to another.
Recommended Articles
This is a guide to Hibernate One to One. Here we discuss the introduction and how does one to one relationship work in hibernate? You may also have a look at the following articles to learn more –