Hibernate Bidirectional Mapping short note

Here is my Hibernate/JPA bidirectional mapping short note.

One To One







Student StudentRegistration
@Id
@Column(name="student_id")
private Long studentId;
@Id
@Column(name="registration_no")
private Long registrationNo;
@Column(name="student_name")
private String name;
@Column(name="level")
private String level;
@Column(name="registration_date")
@Temporal(TemporalType.DATE)
private Date regDate;
@OneToOne
StudentRegistration studentRegistration;
@OneToOne(mappedBy="studentRegistration")
Student student;

Student is the owner, We add owner side property name to 'mappedBy'  of other side.

Database tables created by Hibernate

student
student_id student_name STUDENTRGISTRATION_registration_no

student_registration
registration_no level registration_date

If you want to change STUDENTRGISTRATION_registration_no column name to stu_reg_no add @JoinColumn annotation.

@OneToOne
@JoinColumn(name="stu_reg_no")
StudentRegistration studentRegistration;

  View Sample Code

One to Many/ Many to One 


Employee Department
@Id
@Column(name="emp_id")
private Long id;
@Id
@Column(name="dep_id")
private Long id;
@Column(name="emp_name")
private String name;
@Column(name="dep_name")
private String name;
@ManyToOne
Department department;
@OneToMany(mappedBy="department")
List<Employee> emps;


Database tables created by Hibernate

employee
emp_id emp_name DEPARTMENT_dep_id

department
dep_id dep_name

  View Sample Code

Many to Many








Employee Project
@Id
@Column(name="emp_id")
private Long id;
@Id
@Column(name="project_id")
private Long id;
@Column(name="emp_name")
private String name;
@Column(name="project_name")
private String name;
@ManyToMany(mappedBy="employees")
List<Project> projects;
@ManyToMany
List<Employee> employees;


Database tables created by Hibernate

employee
emp_id emp_name

project
project_id project_name

project_employee
projects_project_id employees_emp_id

If you want to change project_employee table name to pro_emp add @JoinTable annotaion
    @ManyToMany
    @JoinTable(name="pro_emp")
    List<Employee> employees;

  View Sample Code

4 comments:


  1. Hai Author, Very Good informative blog post,
    Thanks for Sharing

    ReplyDelete
  2. Salesforce CPQ Training Course
    Understand Configure, Price, Quote (CPQ) automation with Salesforce. Learn to manage pricing, discounts, and quote generation to streamline business sales processes.

    ReplyDelete